As you know on shell prompt if you type "./shift_test.sh one two foo" then shift_test.sh is executed and three arguments are passed into it one,two and foo corresponds to $1, $2 and $3 respectively.
That is,
$1=one
$2=two
$3=foo
Now suppose I want to make shift the position parameter by one or two. To do the task we need to use shift command. In fact, simple use of the shift command moves the current values stored in the positional parameters (command line args) to the left one position. So, after usage shift command we will get,
$1=two
$2=foo
and $3 becomes null.
We can also do shift the positional parameters by 2. In that case we have to write
shift 2
And after shift by 2 position values would be,
$1=foo
and $2, $3 become null.
A simple example of shift command is show below which will shift the positional parameters by 1.
# vi shift_test.sh
echo "Current positional parameters \$1=$1, \$2=$2, \$3=$3"
shift
echo "after shift by 1 it becomes : \$1=$1, \$2=$2, \$3=$3"
# chmod +x shift_test.sh
# ./shift_test.sh one two foo
Current positional parameters $1=one, $2=two, $3=foo
after shift by 1 it becomes : $1=two, $2=foo, $3=
Usage of shift command in shell script
Before going into shift command usage let's see a simple example of how to convert one number system into another number system.
The format of converting number is,
echo "obase=to_which_number_system_to_convert; ibase=from_which_number_system_to_convert; number_to_convert;"|bc
For example to convert number 15 from decimal(10 base system) to hexadecimal(16 base system) issue,
# echo "obase=16; ibase=10; 15;"|bc
F
To convert number 15 from decimal(10 base system) to binary(2 base system) issue,
# echo "obase=2; ibase=10; 15;"|bc
1111
To convert number 15 from decimal(10 base system) to octal(8 base system) issue,
# echo "obase=8; ibase=10; 15;"|bc
17
Now we want to write a shell script that will convert one number system to another number system.
User will give the number in decimal (with -n syntax) and will provide base system to convert(-b). Shell script will return the number in the defined base system.
For example my shell script name is convert_from_decimal.sh and to convert decimal 15 to hexadecimal it can be called as,
./convert_from_decimal -b 16 -n 15
or
./convert_from_decimal -n 15 -b 16
Script is below.
# cat convert_from_decimal
while [ "$1" ]
do
if [ "$1" = "-b" ]; then
base="$2"
shift 2
elif [ "$1" = "-n" ]
then
number="$2"
shift 2
else
echo "$1 is not a valid option"
exit 1
fi
done
echo "Decimal $number equivalent $base - base system is `echo "obase=$base; ibase=10; $number;"|bc`"
# chmod +x convert_from_decimal
# ./convert_from_decimal -b 16 -n 15
Decimal 15 equivalent 16 - base system is F
# ./convert_from_decimal -n 15 -b 16
Decimal 15 equivalent 16 - base system is F
Related Documents
http://arjudba.blogspot.com/2009/04/trap-command-on-linux-shell-script.html
No comments:
Post a Comment