简体   繁体   中英

How to start a script properly from a starter terminal executed script in Ubuntu?

Assume you have a starter in your panel which starts a script called foo.sh in terminal mode.

foo.sh than starts another script called bar.sh in background.

I run into problems:

First: the name of the written file from bar.sh differs.

Second and main: the bar.sh script is not independent and die when the terminal is closed.

I tested this on an old 16.04. machine.

foo.sh

#!/bin/bash

#read an user input
read -r -t 60 -p ":" foo
echo "$foo"

#call bar script
/home/$USER/bar.sh "10" "$foo" & disown

#show if bar.sh was started
echo $?

#sleep a short time to see the echo's
sleep 3

bar.sh

#!/bin/bash

#sleep some time
[[ -n "$1" ]] && sleep $1

#then write user input to file called output
echo "$2 - sleept $1 seconds" >> /home/$USER/output

If the time to sleep in foo is greather than in bar the output file is written but called output? (with an? at the end).

But if the time is larger in bar then bar is killed when foo finished and the terminal is closed.

Any idea how to set up correctly a background instance of bar.sh? Another terminal which stays open is not a solution to me. THX!

This answer comes from learner on Ask Ubuntu :

"nohup" stands for "No Hungup". As the name suggests, it will continue to run the command without hanging up, even if session is disconnected. It is used to run commands on remote server which would take way long time to complete (backing up a DB etc).

Usually, the logs of script (if any) are stored in ~/nohup.out file. But you can choose to capture the logs, either by appending or replacing the logs of old contents with the new. ">" Single greater than sign will replace old logs with the new. ">>" double greater than sign will append the logs to the end of the file.

I'm using this below format to run the same thing in crontab. In this case, I'm replacing the old logs. /path/to/script_folder/script_name.sh > /path/to/script_folder/logs/script_name.log 2>&1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM