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,$var2existed regular shell variables, not environment variables, scriptscript.shdidn't see them.
- this happened in op's case:
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 errorambiguous redirectin 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 messageno 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
Post a Comment