Bash Shell Script Examples

Revision as of 21:31, 4 February 2016 by Admin (Talk | contribs)

Add Pause Prompt In a Shell Script

Use "read". There is no pause command under bash shell.

#!/bin/bash
echo $1
read -p "Press [Enter] key to continue."
exit 0

The sample script above shows what is entered as a command line parameter and then pauses, waiting for the user to press the ENTER key to continue. This creates a PAUSE.

Require command line parameters

see example:

if [ -z $1 ] || [ -z $2 ] ; then
        echo "newuser: too few arguments"
        echo "Usage: newuser [username] [uid]"
        echo "Adds a new robotz.com customer, for use by admin@robotz.com only."
else
        useradd -r $1 -d /home/$1 -m -n -u $2
fi
exit 0

Detach Command and Run in Background

So if the terminal window is closed, the command continues to execute.

You can append an "&" to the end of the command. This detaches the command from stdin. The & ampersand character is placed right of a space at the end of the command. Keep in mind that the command’s process is still managed by the shell and stdout and stderr are still attached. In some cases the process will be terminated if the shell session is closed. It depends on how the process was written.

When you append the "&" at the end you are able to use the command prompt again, however, output from the process is displayed in the same terminal. You can redirect output to a text file or /dev/null.

processname &> /dev/null &

Now you have your command prompt back and will receive no messages, for the most part.

To see the process running look at the jobs

jobs

You will see it displayed. You can detach it with the "disown" command.

Now to deal with HUP. Use "nohup."





See Also...

Last modified on 4 February 2016, at 21:31