Thursday, August 30, 2012

arguments array for bash script

To list all arguments of a bash script, you can do this:
#!/bin/bash
args=("$@")
for ((i=0; i < $#; i++))
{
    echo "argument $((i+1)): ${args[$i]}"
}
Note that: 
args=("$@") is superior to the sometimes seen args=($@) since the former will not create separate array elements if any of the args have spaces in them (so actually this is a pretty cool way to iterate through a directory with filenames containing spaces)Note that the array index starts at zero, but the command line args start at one, which is why the test in the loop is 'i < $#' not 'i <= $#' and the argument index is offset by 1 in the output.
Ref: http://forums.fedoraforum.org/showthread.php?t=220184
For example, if you want to wrap your own script in qsub, you can write this:

myqsub()
{
    rgs=("$@")
    # if no file write to last argument, use
    # cmd=`echo ${rgs[@]}`

    cmd=''
    for ((i=0; i < $#-1; i++)) {
       rgsi="${rgs[$i]}"
       cmd="$cmd $rgsi"
    }
    cmd="$cmd > ${rgs[$i]}"
    echo $cmd;

    sgefile=`mktemp`

    echo "
    ## script for running a command in a cluster way

    #!/bin/sh
    #$ -V
    #$ -cwd
    #$ -pe single 2
    #$ -o $HOME/sge_jobs_output/sge_job.\$JOB_ID.out -j y
    #$ -S /bin/bash
    #$ -l mem_free=1G

    $cmd

    " | sed 's/^[ \t]*//g' > $sgefile
    qsub $sgefile
}










No comments:

Post a Comment