Solved Help with variables

This doesn't work:-
Code:
export USB="da0"
echo '/dev/$USBp2 / ufs rw 1 1'
and neither does this:-
Code:
export USB="da0"
echo '/dev/${USB}p2 / ufs rw 1 1'

How do I get to output /dev/da0p2 ?
 
There are two problems:
  1. Single quotes don't interpolate variables
  2. Even with double quotes (or no quotes) the shell would look for a variable called USBp2 instead of USB
These should work (tested with sh and zsh on DragonflyBSD):
  • echo "/dev/${USB}p2 / ufs rw 1 1"
  • echo '/dev/'$USB'p2 / ufs rw 1 1'
  • echo /dev/${USB}p2 / ufs rw 1 1
 
Rule of thumb:
  • Within single quotes, no characters are interpreted (except, of course, for the single quote itselfs that terminates the single-quoted string).
  • Within double quotes, three characters are special: \ (backslash), $ (dollar sign) and ` (backtick).
  • When using variables, use curly braces if the name is followed by more letters, digits or underscores that are not supposed to be part of the name. If in doubt you can always use curly braces; it never hurts.
 
Never realised that there was such a difference between single and doubles quotes.
I'm happy with this now:-
Code:
export USB="da0"
echo "/dev/${USB}p2 / ufs rw 1 1"
 
By the way, you can omit the export command. Also, the quotes are not really necessary here because the value does not contain spaces or other special characters.

A simple assignment like USB=da0 creates a shell variable that can be used throughout the script. That's sufficient most of the time.

The export command does the same, but additionally it exports the variable to the process environment, so it is inherited by other commands called from your shell script. For example, when you call awk(1), your awk code can use the variable with the predefined ENVIRON array.

One IMPORTANT thing to note is that the environment can be seen by unrelated processes (possibly even by other users, unless your security settings prevent that). Just type ps -auxwwe to see what I mean. For that reason, you should never export variables that might contain sensitive data. Every exported variable should be considered “public”. Therefore, if in doubt, do not use export. Only use it when you're certain that it is needed.
 
Back
Top