3

This question already has an answer here:

How can I put the output of head -15 textfile.txt to a variable $X to use it in an if command like this:

 if $X = 'disabled' then

?

marked as duplicate by jasonwryan, Graeme, slm, goldilocks, Hauke Laging Mar 28 '14 at 22:31

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3
x="$(head -15 testfile.txt)"
if [ "$x" = disabled ]
then
    echo "We are disabled"
fi

Generally, any time that you want to capture the output from a command into a shell variable, use the form: variable="$(command args ...)". The variable= part is assignment. The $(...) part is command substitution.

Also note that the shell does not do if statements in the form if $X = 'disabled'. The shell expects that a command follows the if and the shell will evaluate the return code of that command. In the case above, I run the test command which can be written as either test ... or [ ... ].

Many consider it best practices to use lower-case variables for shell scripts. This is because system defined variables are upper case and you don't want to accidentally overwrite one. On the other hand, there is no system variable called X so it is not a real problem here.

Not the answer you're looking for? Browse other questions tagged or ask your own question.