Scripting: Difference between revisions
No edit summary |
|||
Line 35: | Line 35: | ||
to the n-th arguments if present. $# is the number of command line arguments passed to the script. | to the n-th arguments if present. $# is the number of command line arguments passed to the script. | ||
$> cat .get_users2.sh | $> cat ./get_users2.sh | ||
#! /bin/bash | #! /bin/bash | ||
if [ $# == 0 ] ; then echo "Usage: ./get_users2.sh <filename>" ; exit 1 ; fi | if [ $# == 0 ] ; then echo "Usage: ./get_users2.sh <filename>" ; exit 1 ; fi | ||
Line 43: | Line 43: | ||
# extract user names | # extract user names | ||
cat $filein | awk -v FS=":" '{print $1}' | cat $filein | awk -v FS=":" '{print $1}' | ||
Now, this second version of the script needs to be run as: | |||
$> ./get_users2.sh /etc/passwd |
Revision as of 11:03, 25 November 2020
Commands (to be interpreted and executed) can be placed in a text file, called script, to be executed by means of an interpreter
The interpreter is specified in the first line of the script, e.g. by:
#! /bin/sh #! /bin/bash #! /bin/tcsh #! /usr/bin/awk -f #! /usr/bin/env python ...
(Note that while # is in all the above languages a comment, #! is actually used to identify the interpreter).
Bash scripting
Among the many, bash scripting is particularly relevant to us (bash is also the interpreter of the command-line shell we have been using so far).
Unix commands (enriched by bash built-in functions & structures) can be used in bash scripts:
$> cat ./get_users.sh #! /bin/bash -x filein=/etc/passwd # # extract user names cat $filein | awk -v FS=":" '{print $1}'
Note that in order to execute get_users.sh
, we need to change its permissions,
$> chmod a+x ./get_users.sh
When executing, the output fo the script can also be redirected to a file,
$> ./get_users.sh > users.dat
Within the script, $0 corresponds to the invocation name (./get_users.sh, in the example above), $1, $2, .. $n to the n-th arguments if present. $# is the number of command line arguments passed to the script.
$> cat ./get_users2.sh #! /bin/bash if [ $# == 0 ] ; then echo "Usage: ./get_users2.sh <filename>" ; exit 1 ; fi filein=$1 # # extract user names cat $filein | awk -v FS=":" '{print $1}'
Now, this second version of the script needs to be run as:
$> ./get_users2.sh /etc/passwd