This question is about assigning the entire contents of one variable to another variable.
Variable is not being used (sent to echo
, etc.)
No parameter expansion is being done during the assignment.
My question also pertains only to POSIX shell (no arrays being used here).
error="You have an error in your input"
newVar="$error"
# vs.
newVar=$error
# ↑
# └─This assignment is the question. It doesn't seem that quotes are
# needed here in order to assign the entire contents of $error to
# a new variable.
# ┌─(But quotes are required when they're used.)
# ↓
printf "%s\n" "$error"
# => You have an error in your input
printf "%s\n" "$newVar"
# => You have an error in your input
Are there any gotchas I'm missing in just writing newVar=$error
?
Update:
Regardless of what's in $error
, I want to know will that same data carry over into $newVar
without throwing any errors or mangling the data.
$ error="Test * ${1} \n [!a] [[:punct:]] ./test \t \n \\"
$ newVar=$error
# ↑
# └─Does this step ever fail or cause the two variables to differ?
$ echo "$error"
Test * \n [!a] [[:punct:]] ./test \t \n \
$ echo "$newVar"
Test * \n [!a] [[:punct:]] ./test \t \n \
printf
-- if you give it one "Argument no matter how many spaces, in quotes" then it will print the formatted values only once. If you instead give printf an unquoted variable with spaces in it, then it will repeat the format string for each. – Jeff Schaller Aug 05 '15 at 16:41printf "%s\n" "$var"
, becauseecho "$var"
is less predictable/reliable when$var
begins with dash (-
) or contains backslash (\
). (And of courseprintf "$var"
is unforgiving if$var
contains percent (%
) or backslash (\
).) – G-Man Says 'Reinstate Monica' Aug 05 '15 at 19:21