bash - Command works normally in Shell, but not while using a script -


i used command in bash shell:

printf $var1 >> `printf $var2` 

and worked. when write script file , run in shell, not work. file "script.sh" contains this:

#!/bin/bash printf $var1 >> `printf $var2` 

and output in shell is:

script.sh: line2: `printf $var2`: ambiguous redirect 

i don´t know, how possible, because command absolutely same. , of course, run script on same system , in same shell window. thank help.

there 3 points worth addressing here:

shell variables vs. environment variables:

  • scripts (unless invoked . / source) run in child process sees parent [shell]'s environment variables, not regular shell variables.

    • this happened in op's case: $var1 , $var2 existed regular shell variables, not environment variables, script script.sh didn't see them.
  • therefore, child process see parent shell's shell variables, parent must export them first, result of (also) become environment variables: export var1=... var2=...

bash's error messages relating output redirection (>, >>):

  • if filename argument output redirection - unquoted command substitution (`...`, or modern equivalent, $(...)) - i.e., output command - bash reports error ambiguous redirect in following cases:

    • the command output has embedded whitespace, i.e., contains more 1 word.
    • the command output empty, happened in op's case.
      • as aside: in case, error message's wording unfortunate, because there's nothing ambiguous missing filename - cannot work, because files need names.
  • it advisable double-quote command substitutions (e.g., >> "$(...)") , variable references (e.g., "$var2"): allow return filenames embedded whitespace, and, should output unexpectedly empty, you'll (slightly) more meaningful error message no such file or directory.

    • not double-quoting variable reference or command substitution subjects value / so-called shell expansions: further, unintended interpretation shell.

the wisdom of using command substitution generate filename:

leaving aside printf $var2 fragile way print value of variable $var2 in general (the robust form again involves double-quoting: printf "$var2", or, more robustly, rule out inadvertent interpretation of escape sequences in variable value, printf %s "$var2"), there no reason employ command substitution begin with if that's needed variable's value:

>> "$var2" enough robustly specify value of variable $var2 target filename.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

android - Keyboard hides my half of edit-text and button below it even in scroll view -

css - Make div keyboard-scrollable in jQuery Mobile? -