Bash: Read file that contains a star (*)
2014-07
I'm to read the contents of a file in a variable. Doing the following is great:
content1=$(<content-1.html)
However, if that file contains a star (*), instead of reading it properly, it replaces it with the list of files in the working directory.
So, if the file contains the following:
var randomFirst = (Math.floor( Math.random() * (items.length) ) );
Reading it turns it into the following:
var randomFirst = (Math.floor( Math.random() backups compile.sh content css favicon.ico img libs output template.html template_compiled.html (items.length) ) );
How should I read the file to make sure special characters are not interpreted?
Thanks,
The simple answer is to use double-quotes:-
content1="$(<content-1.html)"
echo "$content1"
Double-quotes allow the expansion of variables, but not of file masks. The quotes do not appear in the expansion. So always use double-quotes when referencing content1.
In fact, the first statement does not strictly need the double-quotes, as bash does not rescan an input line, but they do no harm.
So your problem is not with reading the file, but with how you use its contents.
I have a one-line file with a value stored as a string in it:
server-name-2009-August-9-AMI
The file name is server_name
. What's the shortest, most elegant way to rad this value into a variable with bash script?
You can do a "useful use of cat" ;)
VAR = $(cat $(dirname $0)/server_name)
This will put the content of "server_name" file, located in the same directory as your script, into $VAR. Works regardless of where you run the script.
You can use the read
command. If you don't provide any variable, the line gets saved automatically into the variable REPLY
in Bash. If you provide a singe variable, the line gets saved into that variable. If you provide multiple variables, Bash will split the line as words (the splitting is done on whitespace), trying to put one word into each variable. (If there are more words than variables, each variable gets one word, but the last gets the rest of the line.)
Example:
telemachus ~ $ read < buff
telemachus ~ $ echo $REPLY
#!/usr/bin/env perl
telemachus ~ $ read LINE < buff
telemachus ~ $ echo $LINE
#!/usr/bin/env perl
Note that the variable is assigned without a dollar sign (REPLY
or LINE
), but when you use it, you need $REPLY
or $LINE
.
So you would want something like this:
read SERVER < /path/to/server_name
I recommend that you use the full path of the file that you want to read rather than assuming that the two scripts will be in the same directory.
I won't swear that this is the most elegant solution.