I need to use some vars in a script where I use tail
and head
, my script works when I type it in the terminal but when it is in a .sh
file I get this error from the head command:
JavaScript
x
head: option requires an argument -- n
usage: head [-n lines | -c bytes] [file ]
The error comes from this pipe of my script:
JavaScript
head -n $LINE
I tried using variables in another script where only declaring it in the terminal worked. A friend of mine told me to do this, it works but I don’t understand why.
JavaScript
export LINE=15
Advertisement
Answer
I’m not sure which part you are confused about, but here’s what’s going on. head -n $LINE
is expecting an integer so if $LINE
is empty then head -n
has no idea how many lines you want. Example:
JavaScript
(pi5 212) $ unset LINE # make sure $LINE is empty
(pi5 213) $ echo $LINE # show it is empty
(pi5 214) $ head -n $LINE < /etc/motd # see what happens if we try this
head: option requires an argument -- 'n'
Try 'head --help' for more information.
(pi5 215) $ echo "head -n $LINE < /etc/motd" # this is what the shell sees
head -n < /etc/motd
(pi5 216) $ export LINE=1 # try it again with LINE set to an integer
(pi5 217) $ echo $LINE
1
(pi5 218) $ head -n $LINE < /etc/motd
# ___________
(pi5 219) $ echo "head -n $LINE < /etc/motd" # it worked! display what the shell sees.
head -n 1 < /etc/motd
(pi5 220) $
If your question is about why you need to use export ...
then that’s a function of your shell. Here’s an example:
JavaScript
(pi4 594) $ cat /tmp/x.sh
#!/bin/sh
echo "$foo"
(pi4 595) $ echo $foo
(pi4 596) $ /tmp/x.sh
(pi4 597) $ foo="bar"
(pi4 598) $ /tmp/x.sh
(pi4 599) $ export foo="bar"
(pi4 600) $ /tmp/x.sh
bar
It’s explained here:
JavaScript
(pi4 601) $ man sh
When a simple command other than a builtin or shell function is to be executed,
it is invoked in a separate execution environment that consists of the following.
Unless otherwise noted, the values are inherited from the shell.
o shell variables and functions marked for export, along with variables
exported for the command, passed in the environment
export [-fn] [name[=word]]
export -p
The supplied names are marked for automatic export to the environment
of subsequently executed commands.