« Home | Linux Renaming Sets of Files » | Separate Shell Command history » | NFS between Solaris & Linux » | How To Set Up Database Replication In MySQL » | My sysadmin toolbox » | Network Monitoring with Zabbix » | Preventing SSH Dictionary Attacks With DenyHosts » | How do I scan my Linux system for rootkits, worms,... » | Convert man pages to text » | Poor Mans Raid & Clone Script Tutorial » 

Tuesday, April 04, 2006 

Accessing Positional Variables

Accessing positional variables from the left is simple using Bourne, bash, or KornShell93.
ksh88 will not work and csh's syntax I won't cover it.

You can use the form of ${*:1:1} where the 1st 1 is the number of which positional variable you want to access and the 2nd is the number of variables following it that you want.

So, if you type:

set a b c d, echo ${*:3:1}

will give you c.

You can be sneakier using a looping construct. This will give you the positional parameters in order:

for i in 1 2 3 4
echo ${*:$a:1}

Suppose you want to reference the 2nd to last positional parameter.
Try ${*:$#-1:1}.

${*:$#:1} gives you the last one. Even sneakier, here's the positional variables in reverse order.

for i in 1 2 3 4
echo ${*:$#-$i:1}

Beware: different shells act slightly different. Bash, for the above example of set a b c d, gives d for echo ${*:$#-5:1} while ksh gives ksh.

Links to this post

Create a Link