Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x

Shell Scripting

The term 'shell' refers to a general class of text-based command interpreters most often associated with the UNIX and Linux operating systems. Popular shells include Bourne, Debian Almquist (dash), Korn (ksh), Bourne Again (bash) and the C shell family (csh). Some view the DOS 'cmd' prompt as a minimal shell of sorts. It is also possible to install Cygwin on Windows and emulate a full Unix environment with complete shell capabilities. Terminal emulators, such as xterm, GNOME Terminal and OS X Terminal, can be used to access shell.

Share tech news, updates, or what's on your mind.

Sign up to Post

Hi Experts,

I am trying to remove the trailing characters like newline and CR before entering the value into a variable. The value in this variable will be entered into csv file

I did

a=`cat nohup.out|sed ':a;N;$!ba;s/\n//g'`

I am still getting \n or something when the data is put into the csv and the next variable is going to next line of the spreadhsheet.

Please let me know if there is a better way to avoid the next line
0
On Demand Webinar: Networking for the Cloud Era
LVL 10
On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Hello,

I have a powershell script which essentially "works" but with one caveat.

This script queues all the mailboxes to export immediately (i.e. if my text file contains a list of 15 mailboxes then the script queues all 15 mailboxes to export immediately).

The problem I have found is that when the server is trying to export more than one mailbox concurrently, some of the mailbox exports fail.

So I would like a way to either:

1. Modify the script to only perform one export at a time or
2. Configure some setting in Exchange so that only one New-MailboxExportRequest is executed at a time (I've had a look at the settings for this cmdlet and cannot see an option to do this)

$Export = Get-Content C:\Mailboxes.txt
foreach ($i in ($Export)) {New-MailboxExportRequest -ContentFilter {(Received -lt '01/09/2017')} -BadItemLimit 200 -AcceptLargeDataLoss -Mailbox $i -Filepath "\\SERVER\Mail\$($i).pst" }

Open in new window


Thank you
0
Experts - I’d like to create a Linux/Unix read-only-root role for Auditors, InfoSec and Tech Ops, so they can examine a system without risk of breaking anything.
-      Using sudo or Centrify, we can grant the privileges to run some commands as root, e.g.  ls, cat, cksum and tail –f
-      I don’t want to allow root privileges for e.g. find, view or more/less, as they can be used to modify a system

Creating the role is easy; Making it easy to use is harder
-      `sudo cat filename |less` would work fine – the `cat` is run as root, the `less` as the unprivileged user. I can create a little script utility called something like “Auditors_less” to remove the need to remember the syntax.
-      `dzdo cat filename > ~/my_copy_of_filename` would work for the same reason, and give them a local copy to work with. Call it “Auditors_cp” or just “Acp”
(`dzdo` is the Centrify equivalent to sudo)

Replacing the functionality of `find` is the part I can’t figure out. The output of `find` gives the full path to a file. `find` also allows you to select on ownership, permissions etc., but that part could be replaced by
`dzdo ls -l |grep {pattern}`

So a scriptlet that takes a starting directory as input and produces output in the form
/path/to/file      : ls –l output of file
would be great, as grep can filter the output, e.g. for globally writeable files/directories

I’ve found similar questions on formatting `ls -lR` output on stackoverflow.com, but no usable answers – general opinion seems to be…
0
I have a question where i need to write a script which can search the following hives and delete any String value names which match my criteria.

i need to be able to search the entire HKU hive and HKLM

Example, i need to delete any key name that would be called "Malware A" and another one called "Malware B"
They tend to be listed under these directories below but if theres a way to search the entire registry that would be great

HKU\S-1-5-18\SOFTWARE\MICROSOFT\WINDOWS\CURRENTVERSION\RUN
HKU\S-1-5-21-1172670090-1033165640-4219323903-500\SOFTWARE\MICROSOFT\WINDOWS\CURRENTVERSION\RUN
HKLM\SOFTWARE\WOW6432NODE\MICROSOFT\WINDOWS\CURRENTVERSION\RUN

I would prefer to be able to launch the script easily via CMD if possible open powershell via CMD
0
Hi Team,

We have folder called /opt/app
inside /opt/app we are running applications as elasticsearch and kibana in below respective folders.

/opt/app/elasticsearch
/opt/app/kibana

and processes are running in those folders as we.

Due to space issue. Now i want to mount to /opt/app folder without any data loss on the fly?
is it possible or not? if possible could you please suggest me what is the best way to proceed?
0
Have the text file below:

File output.txt

4-character_string_without_space:

1. A few lines of text without character ":"

4-character_string_without_space:

4-character_string_without_space:

4-character_string_without_space:

2. A few lines of text without character ":"
.....

Is there any way to remove the lines with "4-character_string_without_space: and the immediate blank line" if no text follows them? For example.

Original text file:
ABCD:

line1
line2
line3

ABDD:

DDBA:

line5
line6
 
....

Wanted output:
ABCD:

line1
line2
line3

DDBA:

line5
line6
 
....

ABDD: should be removed. Any gurus, is there any concise way to do that? Thanks a lot.
0
Hello All,

I wanted to run the below script

Get-WinEvent @{logname='application';starttime=[datetime]::today } -ComputerName "ABCDEFRR56d" | select timecreated,task, TaskDisplayName

Put the output to a excel file and send email to a distribution list.

Can any one help me with a script?
0
I had this question after viewing Script for testing ping and telnet.

How can i modify this script to test telnet and mutual auth only

Expected Output
Flow ID |       From               |             To                      |          Test           |         STATUS
1            | 192.168.2.26:20  |    192.168.2.27:23       |       Telnet            |             OK
1            | 192.168.2.26:20  |    192.168.2.27:23       |       Mutual Auth |             OK
0
Morning folks, I need a script creating to be run on Server 2012 to look at a few thousand folders and extract the folder permissions to allow me to analyse this in excel.

The reason for this is we are in the process of consolidating (literally) hundreds of legacy domains down into a smaller forest, and we need to understand what folder permissions are around to help get it down.
0
Please provide me with the correct syntax for granting a user full access to another user's Office 365 calendar by using the Office 365 Power Shell.

For example this command grants a single user full access to everyone's calendar within Office 365.

How can this power shell command be modified to grant a single user access to another user's Office 365 calendar?

Get-Mailbox | ForEach-Object {Add-MailboxFolderPermission $_":\Calendar" -User msmith@company.com -AccessRights Owner}

Open in new window

0
Free Tool: Port Scanner
LVL 10
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

I have a script that I am running on a server.  It calls a script on another server which starts three applications on another server and is supposed to return and finish running on the first server (if that makes sense). The problem is it runs the three commands in the script on the remote server, but it doesn't exit and return to the first server.  It hangs.  I have tried an exit, kill $$, kill $0, all to no avail.

Here is the line of code that calls the script on the remote server:
ssh -q ${servertwo} '/ppm/inetsvc/startppm'

Here is the entire script which is called on the remote server.  Again, it hangs at the end and doesn't return to the original server:

#!/usr/bin/ksh
# .profile entries
umask 022
export JAVA_HOME=/usr/jdk1.8.0_25
export ORACLE_BASE=/oracle
export ORACLE_HOME=/oracle/product/db11204
export PATH=$HOME/bin:$JAVA_HOME/bin:$ORACLE_HOME/bin:$PATH
export LD_LIBRARY_PATH=$ORACLE_HOME/lib
export PPM_SERVER_CONF_DIR=/ppm/shared/conf
alias ppmhome="cd /ppm;ls -ltr"

cd /ppm/bin
./kStart.sh -name HPPPM_SVC2
sleep 80
./kStart.sh -name HPPPM_TU2
sleep 80
./kStart.sh -name HPPPM_TU4
kill $0

Any help would be greatly appreciated.

Thanks,
David
0
Hi,

I have a log file that has its entries separated by timestamp:

2017-08-31 12:18:10,362Z [lTaskScheduler4] TRACE c.g.a.v.n.c.r.AbstractRepository          : Ope
2017-08-31 12:18:10,363Z [lTaskScheduler4] TRACE c.g.a.v.n.c.r.CouchbaseOperations         : DBf
2017-08-31 12:18:10,363Z [lTaskScheduler4] TRACE c.g.a.v.n.c.r.AbstractRepository          : Oper
2017-08-31 12:18:10,364Z [lTaskScheduler4] TRACE c.g.a.v.n.c.r.CouchbaseOperations         :
2017-08-31 12:18:10,364Z [lTaskScheduler4] TRACE c.g.a.v.n.c.r.AbstractRepository          : Operation db.read.customer: 1 ms

And I have this command to filter and count certain lines of this log:

cat bug.log | grep notiStatus | grep HandleDownedure | grep "Bion" | grep -v "Executes"  | wc -l


But I need to separate this count for this log file to a count after 2017-08-31 07:00:00.000Z

And also a count before 2017-08-31 07:00:00.000Z

How can I put this in the command line?

Tks,
JT
0
I have a main shell script that gets parameter values from an external file.  I need to start looping through a particular set of parameter values and can't figure out how to make it all come together.  

In test_main_script, I have successfully used/called(?) the external parameter file by putting
. env.vars

Open in new window

at the beginning of the file.  

But now I need to loop through a set of values, and I'm putting the list of values in a text file.  I'm trying to use/call the external parameter file once for each value in the text file.  

Here are the files that I have created.  The loop part almost works (it leaves off the last row), but whereas previously the values correctly passed from env.vars to test_main_script.ksh (before I added the loop), now they don't get passed.  

What am I missing, to get the values to correctly pass from env.vars to test_main_script.ksh?

My background is Oracle development; I'm still learning shell scripting.

Thank you,
Cali

##### test_main_script.ksh #####

#!/bin/ksh -x
# main script
while read -r a b; do
  ./env.vars $a $b

  export start_date
  export stop_date
  export row_id
  export row_name
  echo start_date=${start_date}
  echo stop_date=${stop_date}
  echo row_id=${row_id}
  echo row_name=${row_name]
  echo 'This is the main script'
done < test.txt

exit 0

##### test.txt #####

12 first
345 second
67 third

##### env.vars #####

#!/bin/ksh -x
export start_date='20170703'
export stop_date='20170704'
export row_id=$1
export row_name=$2

Open in new window

0
Hi Experts,
Hope you are doing well. I am trying to run a command from linux to windows using winexe.

I am able to fetch information from windows systems using winexe like the example below wherein the powershell runs remotely and gets information into $x

x=`winexe -U user%pwd //vservername 'powershell.exe Get-WmiObject Win32_ComputerSystem | Select-Object -ExpandProperty NumberOfLogicalProcessors'`

In some systems the command gets stuck in the remote system and does not come back, I would like to add a timeout to the above command, I tried this

x=`timeout 10 winexe -U user%pwd //vservername 'powershell.exe Get-WmiObject Win32_ComputerSystem | Select-Object -ExpandProperty NumberOfLogicalProcessors'`

but does not work.

Could you please help me with putting a timeout such that the command comes back if it gets stuck.

Thanks
Amrith
0
I am trying to create a script that I can use to log into remote pc's, on a domain, with admin privileges and uninstall software and then display a pop-up.

so far I have this: wmic /failfast:on /node:"D:\computers.txt" product where name="Java 8 Update 144" call uninstall /nointeractive

in some cases I also need to delete the registry keys.

 REG DELETE "HKEY_CLASSES_ROOT\Installer\Products\4EA42A62D9304AC4784BF2238110440F" /f

REG DELETE "HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Installer\Products\4EA42A62D9304AC4784BF2238110440F" /f

REG DELETE "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Products\4EA42A62D9304AC4784BF2238110440F" /f

REG DELETE "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\{26A24AE4-039D-4CA4-87B4-2F32180144F0}" /f

can you please help?
0
Dear Experts.

I'm using the following Backup Script:

#!/bin/bash
# directory to put the backup files
BACKUP_DIR=/backup

# MYSQL Parameters
MYSQL_UNAME=bckpusr
MYSQL_PWORD=**********

# Don't backup databases with these names 
# Example: starts with mysql (^mysql) or ends with _schema (_schema$)
IGNORE_DB="(^mysql|_schema$|sys)"

# include mysql and mysqldump binaries for cron bash user
PATH=$PATH:/usr/bin

#==============================================================================
# METHODS
#==============================================================================

# YYYY-MM-DD
TIMESTAMP=$(date +%F)

function mysql_login() {
  local mysql_login="-u $MYSQL_UNAME" 
  if [ -n "$MYSQL_PWORD" ]; then
    local mysql_login+=" -p$MYSQL_PWORD" 
  fi
  echo $mysql_login
}

function database_list() {
  local show_databases_sql="SHOW DATABASES WHERE \`Database\` NOT REGEXP '$IGNORE_DB'"
  echo $(mysql $(mysql_login) -e "$show_databases_sql"|awk -F " " '{if (NR!=1) print $1}')
}

function echo_status(){
  printf '\r'; 
  printf ' %0.s' {0..100} 
  printf '\r'; 
  printf "$1"'\r'
}

function backup_database(){
    mkdir -p $BACKUP_DIR/$TIMESTAMP
    backup_file="$BACKUP_DIR/$TIMESTAMP/$database.sql.gz" 
    output+="$database => $backup_file\n"
    echo_status "...backing up $count of $total databases: $database"
    $(mysqldump $(mysql_login) $database | gzip -9 > $backup_file)
}

function backup_databases(){
  local databases=$(database_list)
  local total=$(echo 

Open in new window

0
Hi All,

Greetings...

According to my work, I need to zip files present in a folder using batch script without using any 3rd party software.

I tried with below code ,but getting the error.error also attached below.

Any help regarding this would be highly appreciated.
'Get command-line arguments.
Set objArgs = WScript.Arguments
Set FS = CreateObject("Scripting.FileSystemObject")
InputFolder = FS.GetAbsolutePathName(objArgs(0))
ZipFile = FS.GetAbsolutePathName(objArgs(1))

'Create empty ZIP file.
CreateObject("Scripting.FileSystemObject").CreateTextFile(ZipFile, True).Write "PK" & Chr(5) & Chr(6) & String(18, vbNullChar)

Set objShell = CreateObject("Shell.Application")

Set source = objShell.NameSpace(InputFolder).Items

objShell.NameSpace(ZipFile).CopyHere(source)

'Required!
wScript.Sleep 2000

Open in new window


This code is present in zip.vbs file. We have to zip the files into Outputfile.zip file.
in command prompt  , I have entered below command

C:\Users\abc>Cscript zip.vbs input path  output path\OutputFile.zip

While executing this ,I got below error. " Path not found error" for both the input and output file path.

It will be helpful if anyone corrects me the mistake which I made in this script.
2
i'll need a Shell script that scans thru creation dates of all patches (ideally only the security ones but
if this is not possible, then all patches) installed in an RHEL 7 server, get the latest one, compute
the difference from today's date & give the difference in number of days & if the difference is
more than 90 days, echo out a message, "It has been more than 90 days since last patch)

Purpose is to check the last patch date & remind Linux admins.  Believe RHEL releases patches
at least every 3 monthly?
0
Hello ,

I want to appy a system command with arguments from variables but i could not find an example any body has experience about this ?


This is what i want to do
system("/bin/bash  /etc/a.sh   %d %d",val1,val2);
0
On Demand Webinar - Networking for the Cloud Era
LVL 10
On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Hi all i am managing email server ,i have user data in mysql. group list in sympa and user detail in active directory. if i want to romove any user from multiple group i do it manually one by one from all group,i want to make it automated through shell script,please suggest me best possible script to remove a user from multipe group and  from sympa,mysql, and ldap at same time.
0
Hey there,

I have an Exchange 2016 Hybrid setup with O365. All active users will be in the cloud, however terminated users will be migrated back to on prem and either left in the database for a term or exported to a PST. What I'm trying to do is to get my powershell script to pause until the batch completes and then continue on with some other tasks. I am aware of the Out-Null option but I don't think that's going to work in this case, as I need to confirm progress/completion after querying the status. I thought about using an Outlook rule that kicks off the remainder of my script after the migration notification is sent out but that relies on an outlook profile. Is it possible to do what I'm looking for or do I need something else in play here?

Thanks!
0
Basically I need to run the script with paths related to the shell script file location, how can I change the current directory to the same directory as where the script file resides?
0
Hi,

I am writing a script which connects via server remotely and run the sql script but the thing is i am passing process ids as paramerters  to kill the process of remote server here is the way i am sending

shell script :
echo "Pid :" ${pid[$i]}
      output=$(ssh -o StrictHostKeyChecking=no oracle@$HOSTNAME -p 9292  "bash -l -c sqlplus @"</home/oracle/process.sql ${pid[$i] )

Following is the sql script :

/as sysdba
            whenever sqlerror exit sql.sqlcode;
            SET HEADING OFF;
            SPOOL processOutput.txt
       
            select DISTINCT
            s.CLIENT_IDENTIFIER
            from v$session s, v$process p, v$sql q
            where s.paddr = p.addr      
            

and p.spid IN ($1,$2)

           and s.sql_id = q.sql_id(+);
            spool off;
            exit;

getting  ERROR at line 5:
ORA-00911: invalid character

line refering the error is hilighted.
0
Hello All,

Below script works fine and gets the output, I am planing to run this script against 50 Machines the output should have hostname/computername column. Thanks for help  

Import-module servermanager ; Get-WindowsFeature | where-object {$_.Installed -eq $True} | Select-Object name, d
isplayname, installstate

Open in new window

0
Every month  we wud like to sftp over  Win 7 n Win 10 patches (.msi  .msu, ??)  to about 20 remote PCs that are located in our supplier/service providers premises as these PCs are npt part of our corporate's AD/domain n we cant Rdp/remote to them for security reason.

Can anyone provide a batch or cmd scripts tt will scan for the presence of msi or msu (or any extensions tt MS patches may come in) in a folder (say c:\MSpat )  n will execute them in silent mode (ie dont need us to input/intervene) but dont reboot after patching.  Ideally, output logs ( >>) or error ( 2>>) to 2 separate logs.  Housekeep away the patch files
0

Shell Scripting

The term 'shell' refers to a general class of text-based command interpreters most often associated with the UNIX and Linux operating systems. Popular shells include Bourne, Debian Almquist (dash), Korn (ksh), Bourne Again (bash) and the C shell family (csh). Some view the DOS 'cmd' prompt as a minimal shell of sorts. It is also possible to install Cygwin on Windows and emulate a full Unix environment with complete shell capabilities. Terminal emulators, such as xterm, GNOME Terminal and OS X Terminal, can be used to access shell.