1

HP-UX *** B.11.31 U ia64 **** unlimited-user license Hello,

var1=abc var2=xyz touch $var1 $var2 $var3 

if the one of the variable is not set the command fails with

ksh: var3: parameter not set 

How do we make the command ignore the variable that is not set/defined and create the files for the variables that are defined. Without if loops. Just within the touch command. Thanks

    2 Answers 2

    2

    You'd get that error message if you had turned the -u option either by invoking ksh as ksh -u or ksh -o nounset or by running set -u or set -o nounset.

    touch $var1 $var2 $var3

    is wrong anyway unless those variables are meant to contain lists of file patterns.

    It should have been:

    touch -- "$var1" "$var2" "$var3" 

    Now, if you want to allow one of them to be empty and not pass it as an empty argument to touch in that case (and work around set -u), you'd write:

    touch -- ${var1:+"$var1"} ${var2:+"$var2"} ${var3:+"$var3"} 

    Another option is to do:

    (IFS=; set -f +u; touch -- $var1 $var2 $var3) 

    With IFS=, we disable word splitting, with set -f globbing, but we rely on the third side-effect of leaving variables unquoted: empty removal. (and we also disable nounset with set +u, all of that in a subshell only).

      0

      I doubt if you can do it just in a line, you can try something like this

      validate_touch() { for value in "$@" do if [ ! -z "$value" ]; then touch $value;fi done } validate_touch new 
      3
      • what about the colon and hyphen combination ":-"CommentedFeb 13, 2015 at 11:35
      • it(colon hyphen) is used to get a default value when the variable is not defined. can we set that to nothing?CommentedFeb 13, 2015 at 11:36
      • In that case, you'd have to add an elif condition to ignore that as well. Are there a limited number of combinations you'd like to ignore?
        – rahul
        CommentedFeb 13, 2015 at 11:38

      You must log in to answer this question.

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.