Thursday, August 30, 2012

arguments array for bash script

To list all arguments of a bash script, you can do this:
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.
For example, if you want to wrap your own script in qsub, you can write this:

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

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


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

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


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

No comments:

Post a Comment