Bash
Detaching a bash command with GNU screen

Detaching a bash command with GNU screen

Sometimes running a bash command on the server can take several hours to complete. In such cases you would like to run the command in background and close the terminal from which the command was started (without terminating the process itself). The best way to achieve that is to use GNU screen’s detaching utility.

In order to run and detach a task (e.g., a bash script), use the following screen command:

screen -S session_name -c "your command here"

For some reason, if you wish to use environmental variables and use them, e.g., to create a new directory, you have to perform these actions before running the screen command itself, see an example below:

export SUBJECT=001_ABAD && export SUBJECTS_DIR=/data/Experiment/$SUBJECT/Analyzed_data/anatomical && mkdir -p $SUBJECTS_DIR

screen -S recon-all_$SUBJECT bash -c "recon-all -s freesurfer -i /data/Experiment/$SUBJECT/NIfTI/anatomical/T1w/T1w.nii.gz -all"

After running the screen command you should see screen’s view, such as the one presented below:

And the command’s output should be displayed there.

Now, you want to detach the session, so you press Ctrl+a (release) and press d (see this answer). Detaching the session will return you to the terminal where you started, and the information about the detached session will be displayed:

➜  current_dir screen -S recon_all_sub bash -c "recon-all -s freesurfer -i /data/Experiment/$SUBJECT/NIfTI/anatomical/T1w/T1w.nii.gz -all"
[detached from 3007853.recon_all_sub]

Now you can safely close the parent terminal (the one you started in). The process will run in the background.

Leave a Reply