Recently encountered a problem,
Execute script, script calls a command, command (Deamon) is a daemon, in order to debug, the daemon mode is canceled. The other commands behind the command (echo "456") cannot be executed.
Deamon-d is initiated in daemon mode, DEAMON-X is initiated in non-daemon mode (monitoring process, dead loop), stdout and stderr are associated to the control terminal.
The script is a.sh
#!/bin/sh
echo "123"
/usr/local/bin/deamon-d & >/dev/null 2>&1
echo "456"
Execute the script with the output as follows:
[[Email protected]]#./a.sh
[[email protected]] #123
[[email protected]] #456
[[Email protected]]#
In accordance with my requirements, Deamon runs in the background. The command behind the Deamon gets run.
Now I'm going to switch Deamon to debug mode, deamon-x, output redirect to/tmp/debug.info file
Modify the a.sh as follows:
#!/bin/sh
echo "123"
/usr/local/bin/deamon-x & >/tmp/debug.info 2>&1
echo "456"
Execute the script with the output as follows:
[[Email protected]]#./a.sh
[[email protected]] #123
[[email protected]] #deamon的输出信息
This is not what I want, the output of Deamon is not redirected to the Debug.info file, and the command behind Deamon is not executed.
After modifying the a.sh as follows, I realized my purpose.
#!/bin/sh
echo "123"
/usr/local/bin/deamon-x >/tmp/debug.info 2>&1 &
echo "456"
The result after execution is
[[Email protected]]#./a.sh
[[email protected]] #123
[[email protected]] #456
[[Email protected]]#
The output information of the Deamon is redirected to the/tmp/debug.info file.
Summarized as follows:
1. Background symbols & must be placed at the end of the entire command.
2. redirect >,>> always follow the emphasis on the directed file
3. If the file output 1 stdout,2 stderr to redirect to another file, it is also followed by the >,>> symbol.
4. If you want stderr to output to a file as well as stdout, use
/usr/local/bin/cmd >file 2>&1
the same meaning as/usr/local/bin/cmd 1>file 2>&1 .
Shell script in the background execute commands &