Search code examples
bashsh

Force word splitting for fallback value in sh/bash


I want use complex command as fallback value, something like this, but do not treat ls -sh as single string.

"${@:-ls -sh}"

Solution

  • Try

    [ -n "${@:+X}" ] || set -- ls -sh
    "$@"
    
    • See How to check if a variable is set in Bash for an explanation of [ -n "${@:+X}" ].
    • set -- ls -sh sets the positional parameters so $1 has the value 'ls' and $2 has the value '-sh'.
    • The code uses only POSIX shell features so it doesn't require Bash.