I have a file with a word written on it. I want my script to put that word in a variable.
How can I do that?
To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...] arg1 arg2 ...'
One way we can write variable contents to a file is to use the echo command along with the redirect operator. In this case, the -e argument applies to the call to echo and is not sent as output to the file. So we only see “some value”.
in several of a million ways...
simplest is probably
my_var=$(cat my_file)
If you use bash and you want to get spiffy you can use bash4's mapfile, which puts an entire file into an array variable, one line per cell
mapfile my_var < my_file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With