john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

Linux script programming

06jan08 -> 09may09

Shell scripts are a text file with commands that is marked as executeable

e.g. %chmod +x scriptfilename

often scripts are named .sh so it is obvious they are a script (but it's not neccesary) The syntax is very close to C programming or DOS batch files - BE AWARE....

SHELL SCRIPTS ARE VERY SPACING & CASE SENSITIVE - less spaces & more return lines are better!

To execute your script, type into the terminal:

./scriptname

Note: If the current directory is in the PATH environment variable you can omit the ./ before the name. If you don't want the script to execute in a subshell (because when the script terminates you lose any changes made to that environment), run the script by prefixing the name with a dot and a space, like so:

. setvar

This tells Bash to run the setvar script in the current shell environment,

Linux Script Arguments / Parameters

These are the the values you pass to a shell script from the command line

They are called "positional variables" and are special, e.g. s $1, $2, $3, and so on.

The name of the currently running script is stored in the $0 variable.

$# The number of arguments

$* The entire argument string

$? The return code from the last command issued

$$ is the process id of the current shell (verify this by typing "ps -f |grep bash")

$? is the exit result (success or failure) of the last command

YOU CAN THINK OF THE $ AS A DEREFERENCE * FROM C PROGRAMMING, e.g. Get the value held at location ... THUS IT IS NECESSARY TO SEE/USE A VALUE FROM ANY VARIABLE

is for comments

note that the below statement, when using [ or ] you must ensure there

is a space before and after the [ and the ]

set -o verbose #echo on //this will show all script commands in the stdoutput set +o verbose #echo off

RIGHT

if [ $variable -eq 0 ]

WRONG

if [$variable -eq 0]

-eq == Equal to -lt < Less than -le <= Less than or equal to -gt > Greater than -ge >= Greater than or equal to

-f file True if file exists and is a regular file -r file True if file exists and is readable -w file True if file exists and is writable -x file True if file exists and is executable -d file True if file exists and is a directory -s file True if file exists and has a size greater than zero.

-n str True if string str is not a null string -z str True if string str is a null string str1 == str2 True if both strings are equal str1 != str2 True if both strings are unequal str True if string str is assigned a value and is not null.

-a or && Performs the AND function -o or || Performs the OR function

echo "enter your case option: 1= ls -l, 2= ps -aux, 3= date," echo "or enter YES in any combination of uppercase and lowercase" read i;

case $i in 1) ls -l;; 2) ps -aux;; 3) date;; Y|y) echo "you typed Y or y";; [Yy][Ee][Ss]) echo "you typed Y or y, E or e, S or S";; esac

until false # could also be while false do execute commands done

for variable in list do execute commands done

The command "seq 80 100" prints a list of number from 80 to 100.

You can use built in commands in your scripts, e.g. the date function

mkdir /bin/date +%y%m%d //lower case y for 2 digit year

ls -al > /bin/date +%Y-%m-%d--%H-%M //very important, the ` is a unique quote

You can also save the results from a built in command in a variable

DATE = /bin/date +%y%m%d

EXAMPLE SCRIPT TO ADD AN FTP USER (showing all commands to stdout)


!/bin/bash

set -o verbose #echo on

arg_count=$# if [ $arg_count -ne 2 ] then echo "Usage:- $0 username password" exit fi

echo "Create a new folder for the ftp user" mkdir /ftpshare/$1

echo "Create the new ftp user with the given password" useradd -d /ftpshare/$1/ -p $2 $1

echo "Check that the user has been created" cat /etc/passwd

echo "Add the user to the vsftpd user list" $1 >> /ftpprotected/vsftpd.chroot_list

echo "Check that ths user has been added to the vsftpd user list" cat /ftpprotected/vsftpd.chroot_list

chown $1:$1 /ftpshare/$1

echo "Ensure the new ftp user has ownership of their new ftp folder" ls -al /ftpshare/$1

/etc/init.d/vsftpd reload /etc/init.d/vsftpd restart

set +o verbose #echo off


EXAMPLE OF A SCRIPT TO READ PARAMETERS AND USE CASES

!/bin/bash

the above line is the required first line of a bash shell script

this script works best when typed in ./scriptname.sh parameters are here

clear echo "Number of passed parameters: $#" echo "Contents of passed parameters: $*" echo "\$0 is $0" # escape character is /

counter=0 declare -a array echo counter" is "$counter

if [ $# == 0 ] then # then must be on a separate line echo "You have passed no parameters, that's no fun! Try ./scriptname.sh parameters are here" else echo "Listing of the parameters on a separate line using the command shift:" loop=0 while [ $# != 0 ] # could also be ["$*" -ne "" ] do echo $1 array[counter]=$1 shift counter=$((counter+1)) # could also be i=expr $i + 1 using the backtick character # could also be (( i += 1 )) note that (( $i += 1)) is INCORRECT (no $ and no space) done echo $counter" parameters displayed backwards (captured by an array):"

for (( i=$((counter-1)); i>=0; i-- ))
do
    echo ${array[$i]}
done

fi

note that fi ends the if statement

echo "enter your case option: 1= ls -l, 2= ps -aux, 3= date," echo "or enter YES in any combination of uppercase and lowercase" read i;

case $i in 1) ls -l;; 2) ps -aux;; 3) date;; Y|y) echo "you typed Y or y";; [Yy][Ee][Ss]) echo "you typed Y or y, E or e, S or S";; *) echo "DEFAULT: not a menu option";; esac


for user in $(cut -f1 -d: /etc/passwd); do crontab -u $user -l; done



  • « Security airodump notes
  • Linux script ftp non interactive mget subdirs »

Published

Feb 6, 2010

Category

linux

~972 words

Tags

  • linux 249
  • programming 9
  • script 19
  • scripts 63