linuxbashshellpositional-parameter

"$1" is empty when running bash -c scriptname arg


I was trying to develop a simple bash script where one positional parameter is used. But for no reason the parameter is empty. The bash script is given bellow.

#!/bin/bash
ulimit -s hard
if [ "$1" != "" ]; then
    echo "Positional parameter 1 contains something"
else
    echo "Positional parameter 1 is empty"
fi
root="$(dirname "$(readlink -f "$1")")"
dir="$(basename "$(readlink -f "$1")")"
path=$root/$dir
echo $path

While I was running the script file in the following way, it shows empty strings.screenshot of output

I was using bash -c command since i need to run the bash script from a java code using ProcessBuilder Class.

I know very little about bash scripting and I tried in more simpler way like:

root=`dirname $1`
dir=`basename $1`
path=$root/$dir

But the result is all the same.


Solution

  • From the bash documentation:

    If the -c option is present, then commands are read from string. If there are arguments after the string, they are assigned to the positional parameters, starting with $0.

    The emphasis here is in the original, which is nice since it's a bit surprising, but we can see it with:

    bash -c 'echo zero: $0 one: $1 two: $2' a b c
    

    which produces:

    zero: a one: b two: c
    

    as output.

    In short, you should be inserting an extra argument to take up the $0 position, or adjusting all your argument numbers (I'd go for the former solution).