Search code examples
bashparameter-expansion

cd ${1:-.} what does that mean


#====================script 5 -- ls reccurssive avec cd =======
#!/bin/bash
exec 2>/dev/null # redirige stderr pour toute la suite
# au cas ou le script est invoque sans argument $1
# n'existe pas, la commande suivante devient cd .
cd ${1:-.} # problem that i miss understood
for i in * ; do
if [ -d $i ] ; then
echo "$PWD/$i/ <-- repertoire"
$0 $i # le script s'invoque lui-même
else
echo $PWD/$i
fi
done

===================================================

can someone explain to me this cd ${1:-.} what is mean how to use it if there any article explain this


Solution

  • ${a:-b} means, as explained in the manual, to use $a if it is defined, and otherwise just b.

    The idea here is that if the script received an argument, $1 will be defined, and the script will cd to that directory. If the script didn't receive an argument, ${1-.} will expand to the provided default value, ..

    Since . means the current directory and cd . is a no-op, this basically means, "cd to $1 if available, otherwise simply carry on with the script."