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


Im trying to develop a script that will strip the msexchangeguid attribute from a particular OU only, once a week as a scheduled task.
Im almost there.

The first part of the script successfully identifies all users in that OU that has a non-NULL msExchangeGUID
Get-ADUser -SearchBase "OU=Disabled-Objects,dc=my,dc=domain,dc=com" -filter * -Properties * | ? {$_.msExchMailboxGuid -ne $null}

Open in new window

The next part of the linked script will just give me the SAMAccountNames of those users with a non-Null msExchangeGUID from the above command
Select-Object SamAccountName

Open in new window

Put the final part of setting the attribute to be Null (0000) doesnt take the SamAccountNames for action
Set-RemoteMailbox  -ExchangeGUID 00000000-0000-0000-0000-00000000000

Open in new window

Here it is in one non-functioning line.

Get-ADUser -SearchBase "OU=Disabled-Objects,dc=my,dc=domain,dc=com" -filter * -Properties * | ? {$_.msExchMailboxGuid -ne $null} | Select-Object SamAccountName | Set-RemoteMailbox  -ExchangeGUID 00000000-0000-0000-0000-000000000000

Open in new window

I also thought about i could put the output of the first two lines into a text file, that I think use as a variable
Get-ADUser -SearchBase "OU=Disabled-Objects,dc=my,dc=domain,dc=com" -filter * -Properties * | ? {$_.msExchMailboxGuid -ne $null} | Select-Object SamAccountName > users.txt

Open in new window

$users=Get-content users.txt
Foreach($user in $users){
get-aduser $user| set-aduser -clear msExchMailboxGuid

Open in new window

But the users.txt has trailing whitespaces after the username so the  
get-aduser $user| set-aduser -clear msExchMailboxGuid

Open in new window

looks like
get-aduser "USERNAME        "| set-aduser -clear msExchMailboxGuid

Open in new window

when it runs. It fails on the excess whitespaces.

Any help from Powershell gurus out there?
Fundamentals of JavaScript
LVL 12
Fundamentals of JavaScript

Learn the fundamentals of the popular programming language JavaScript so that you can explore the realm of web development.

I'm trying to parse out the hostname of the machine from /etc/hosts from /etc/hosts in order to find out the IP of the server and only use host to lookup the IP if it's not in /etc/hosts. There are multiple NICS on the server.  The issue is in the /etc/hosts it looks like this gonzo gonzo.domainxxx gonzo-bk gonzo-bk.domainxxx gonzo-sn gonzo-sn.domainxxx
I've used grep -w to try and grep out the hostname but it still returns all the IP's in /etc/hosts. Is there a better way to parse this?


# Get the server's IP address
if [ $( cat /etc/hosts | grep -cw $(hostname)) -ne 0 ];then
            # (1)Read the IP from the hosts file
           MGTIP=$(cat /etc/hosts | grep -w "$(hostname)" | awk '{print $1}')
       # (2)Get the IP with nslookup if it's not in /etc/hosts
       MGMTIP=$(host "$(hostname)" |  awk  '{print $5}')
I'd like to determine in my bash script which NIC the default gateway is on in order to determine if i need to add static routes via the script or not. Since there are two instances of in the routing table where the default gateway is I'n trying to determine the NIC mentioned in the routing table where there are two instances of Then if it matches ${DftNic} below I no I won't have to add static routes on the server. Scratching my head on this so any help would terrific.

DftNic=$(ip route show | grep default  awk '{print $7}')
How do you append the output value of a command  that is run plus the value of other variables to a log file in a bash script?
This is what I have just now

date=$(date '+%d%m%Y:%H%M)
runbinary  2>&1 | tee -a ${installlogfile.txt}  <- instead of this i want to be able to append also ${date} and ${host} to the installlogfile.txt but tee -a with multiple variables doesn't work. Any ideas on how to do this in bash would be much appreciated. If i echo or print the variables before i run the command there would be newline characters and I would like the output in the log file to be $(hostname) ${date} output from the command.
Hi Experts,

I wrote a bash script that will execute my php code every 30 min via cron job. For some reason when check the process via the ps aux | grep myphp.php, I can see more than one process that are running the same php code. Is there a way for me to ensure that there is only a single process that executes my code instead of having more than one process running the same code? Thanks
I'm having trouble with an Expect script on Red Hat Enterprise Server 6.10.  I would think that the script below would spawn SFTP, then send the password.  I'm getting a Password error, which I am guessing is due to lots of escapable characters.

The script below gets me a "permission denied" error.  My password ( I changed some characters) is something like  r10@4g@$^#a&r*a^^$%  .  I have tried escaping the 'special' characters with \ and also tried escaping every character (so it looks like \r\1\0\@\4\g\@\$\^\#\a\&\r\*\a\^\^\$\%).  When I manually connect to the site and manually enter a password it works fine.

Can someone tell me what I might be missing?

Thanks for any advice you can provide,


spawn sftp
expect "username\\'s password: "
send "r10@4g@$^#a&r*a^^$%\n"

Need an automated way to create Azure Dynamic Security Groups using PowerShell. These groups needs to be created based on an AD attribute i.e employee number. Any thoughts?
Hi Experts,

I have linux script which is working fine for creating password protected zip file (zip file will contain csv file) .Please find the same below.
Zip -e -rj  /input/file/path/*.csv 

Open in new window

This command will ask user input ,ie password.It will be like below.
Enter password:

Open in new window

 we need to provide password..Then it will ask for confirmation like this
Verify password:

Open in new window

again we need to provide password..Done..It will create a password protected zip file.

Now I need to automate this script..It should not ask for user input..
Can anyone help me how to write script for automating this task.
Any help regarding this would be highly appreciated.

Thanks in Advance.
We are trying to create an sftp (or lftp) script on a cloud-based server.  There are two things that are complicating this:
1. The cloud-based host does not allow "expect" to be installed
2. The remote host has our ssh key installed on it.  Any SFTP or LFTP connection is requiring that I enter the passphrase for the key.
2a. The remote host still requires a password for an SFTP connection, even with the ssh key installed.

I'm trying to figure out how to write a script that will send the passphrase and the password to authenticate, and then send files to the remote server.

Any help would be greatly appreciated!


I am sure this has been answered several times over on this site:

I have a script that has about 10 columns of information. when run the script from a "Maximized" Powershell window, I get all of the output from all 10 Columns. When I run that same script from a Powershell Prompt running in "Windowed" Mode, I run into an issue where I get about 7 of the 10 columns.

Is there a way to script a function that will "Simulate" the Full Screen output inside a script running in "Windowed Mode"?

An Example of this :

$code = .\Script.ps1|ft -autosize

Open in new window

if I execute the script in a minimized window, I get a truncated output  in $code where if I run the same code in a Maximized Window I get the Full output stored to $code

I know you can do the following :

$code = .\Script.ps1|ft -AutoSize |Out-String -Width 4096

Open in new window

This will give you the full output, however I need to be able to take


Open in new window

and have the Table structure still intact which won't happen if I convert to string.  **Suggestions**?
Exploring SQL Server 2016: Fundamentals
LVL 12
Exploring SQL Server 2016: Fundamentals

Learn the fundamentals of Microsoft SQL Server, a relational database management system that stores and retrieves data when requested by other software applications.


I am using ShellExecute  to open  Brother label printer file.  The code works perfectly!

Often, I need 2 or more identical labels.    In such cases, I would like to direct the printer job to print multiple copies per Shell Execute command (see code).
The reason for this is that  label printer produces waste at the beginning of each print job (by design).    If I print multiple copies then waste is reduced.

I appreciate any help.
Thank you.

Option Compare Database
Option Explicit

Const Dir As String = "C:\!!Tools\Microsoft Access\Labels"
Const TheFile As String = "P- 12MM OLT - Cable - CSP.lbx"
Const SW_SHOW = 5
Private Declare Function ShellExecute Lib "shell32.dll" _
Alias "ShellExecuteA" (ByVal hwnd As Long, _
ByVal lpOperation As String, ByVal lpFile As String, _
ByVal lpParameters As String, _
ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long

Private Sub btnPrint_Click()
    ShellExecute Me.hwnd, "print", Dir & "\" & TheFile, vbNullString, vbNullString, SW_SHOW
End Sub

Open in new window

Hi Expert

I have an Office 365 that uses several domains (,,,, etc...)
Mailboxes can can have one or more aliases using these domains.

I am wanting to change the user principal email address of all users whose current user principal email address is to become I do not want to change any mailboxes that have or as their UserPrincipalName

If possible, I would like to also search for and add the domain with there are aliases using

... And finally, I would like to have a test mode so I can do a test run before I go and blast every mailboxes in this tenancy with the wrong details!

Here are are a couple of examples
  • Stays as is
  • Add,
  • Make the UserPrincipalName,
  • and leave as an alias which has also an alias of
  • Add and to the mailbox
  • Leave & as aliases
  • Make his UserPrincipalName

Note: I did some reasearch before posting this question. I found something similar in ... but it goes through ALL the mailboxes rather than the mailboxes with one given domain.

Can you assist?


I recently got some help writing a powershell script that listed all my AD users with their display name, ad account name and email address. Now I have a request for a similar list but this time a column for first name, last name and limited to active users only. Then the same thing with only deleted users. I supposed another column for active users Y or N would also be acceptable if it is easier. There is the last script  Get-Mailbox -ResultSize unlimited | select name, SamAccountName, primarysmtpaddress | Export-Csv c:\results.csv

I assume there must be a parm for first name and last name, but how can I determine if an account is active or disabled?
Dear Experts,

What is the best way to deployment network printers with presets to mac clients?
On Windows we use a print server with printing defaults and all clients connected through the print server gets those presets.

We need to get a similar experience to our Mac users.

The preset is pretty easy actually:  We are telling the printer to print the first page of every document from tray 2 and every following pages from tray 3 or 4.

I would like to deploy the printer via MDM. I think a script would be the best solution, but couldn't find the option to print the first page differently.

I know you can set this option through word settings, the problem here is, that I can't deploy this is a proper manner.

I was also thinking about an AppleScript in combination with Automator.  

Let me know what you think about my ideas.

Regards SGTA14
Having an issue with some BASH scripts --

crontab has a script it runs every 10 minutes and is set to send stdout & stderr to /dev/null.  

However, it runs some sub-scripts and service restarts and these subscripts are ignoring the redirect to null and generating  unnecessary emails.

What I am not understanding is how stdout & stderr are inherited if at all ?   >/dev/null &2 > 1  by bash scripts run inside a bash script.

Looked at a lot of google links but they are no help.  

I'm working in Oracle Linux 7.   We are moving to this environment from AIX and I'm trying to run the shell scripts in Linux that worked fine in AIX.

One of the scripts passes variables to another shell script by doing "su - oracle" so that the called script will run in Oracle's environment since it does sqlplus to the database to execute a procedure.

For some reason, when using the "su - oracle", the variables do not get passed.  Grrrr

The calling script, named "read_log", is executed by root and passes the variables this way:

 su - oracle -c /dbscripts/run_SQL_insert_proc $UOWNER $UTABLE_NAME $UCOLUMN_NAME $COLUMN_VALUE

The called script, named "run_ora_proc" is owned by oracle and does the sqlplus.   I do an "echo" at the beginning of the script but the variables are empty.  The $0 does show the script name though.

echo "passed variables are " "$0" "$1" "$2" "$3" "$4"

Screen output is:

passed variables are  /dbscripts/run_ora_proc

The shell environment for both root and oracle users is "bash".

What am I doing wrong?
I must delete queue on WebSphere MQ - IBM ,
What are the commands to use on an AIX server?
Hi Team,

I need to validate the date in the below format dd-MON-YYYY  in a shell script. Iam very new to shell script, Any help will be helpful.
28-Feb-2009 , I want to make sure , the date for the feb month is valid .

Any help is really appreciated.
Anyone can share an efficient script (Javascript or any other) that
does BitCoin mining?
Introduction to Web Design
LVL 12
Introduction to Web Design

Develop a strong foundation and understanding of web design by learning HTML, CSS, and additional tools to help you develop your own website.

Dear Experts,

On AIX I need to compare 2 files holding percentage space usage:


hn5691    :   /appli/oltb/apache/logs     72 %
hn5785    :   /appli/logs/REPORTING     38 %

If the percentage in the second file is 10% higher than in first file it should write that in a file (so that can be mailed).
Idea is to catch a looping process.

I'm not enough into awk to make it work, your help is appreciated.
I attach 2 files to work with.

Many thanks in advance.
Hi guys

We have an Exchange 2010 environment on Windows 2008 R2.

How do you export all of the mailboxes, their usernames/aliases but also the organisational unit that their usernames are part of into a CSV?

You already helped me export the mailboxes and their usernames, which worked great. I would like to add organisational units into that CSV also, is this possible?

Thanks for helping
hi guys

So I got some help from EE experts to run a command in Exchange shell to export all mailbox statistics/data.

One of the important things is for me to work out the LastLoggedOnTime so that I can segregate the oldest mailboxes from the actively used ones.

I ran a tool called Inactive Users Tool by Solarwinds and exported it. When I compare the last logged on time of one user from the Exchange shell formula to the data exported from the Solarwinds one, they are different. I have many users who have not logged on for years, but somehow are showing as two days ago in the Shell statistics.

Perhaps the Solarwinds tool is using the Inactive users by looking at a different attribute?

Any ideas on why that would be?

Thanks for helping
Hi guys

We have Exchange 2010 SP3 and I was hoping you could help me pull out an Exchange report that will put everything below into separate columns in an Excel file. It can be ascending or descending based on mailbox size:


AccountName or Alias
MailboxSize (GB)
Mailbox Database Name

Can you help me with this?

Thanks for helping

I would like to request an assistant.

I would like to make a redirect using .htaccess .

The condition that i would like to combined are as follows :

1. redirect any access from /supporttickets.php to

2. redirect any access from  /submitticket.php to

3. redirect any access from   /contact.php to

4. redirect any access to "billing" folder to

5. IGNORE all above rules if the access file are "fpx_indirectcallback.php" or "fpx_directcallback.php"

Appreciates anybody assistant on this issue.
Hi guys

I'm trying to output mailbox sizes, account names, lastlogon time using Exchange Management shell by running the below:

Get-MailboxStatistics  -Server “ServerName” | Select DisplayName, sAMAccountName, LastLoggedOnUserAccount, ItemCount, TotalItemSize, LastLogonTime,  | Sort-Object TotalItemSize -Descending | Export-CSV c:\Folder Name\Filename.csv

I input all of the details where the quotes are, but then for some reason the SamAccountName section is always blank. Can someone help me with that please so that I can have the account names exported also?

Thanks for helping

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.