Skip to content
Advertisement

Exiting bash script without terminating ssh connection

I’m pretty new to bash scripting and I’m attempting to write a script that does some basic operations.

I want to check certain conditions and if they are met, terminate the script. So for example, I want to check whether the zip of files was successful:

echo "Zipping file..."
for file in $fileList;
    do
        echo $file | zip -v $archive -@
        if [[ $? != 0 ]];
            then
                echo "Error creating zip"
                exit 1
        fi
    done

What happens though is that the exit 1 signal causes the ssh connection to terminate as well:

Zipping file...

Command 'zip' not found, but can be installed with:

sudo apt install zip

Error creating zip
Connection to 3.137.7.52 closed.

What’s the correct way to terminate a script without also disconnecting from the server?

Advertisement

Answer

If you wrap it all in a script with shebang #!/bin/bash than exit 1 will be fine but if you run this as a oneliner directly in console then this exit 1 means exit from console, and that would break ssh connection obvy

cat > ziper.sh << EOF
#!/bin/bash
echo "Zipping file..."
for file in $fileList;
    do
        echo $file | zip -v $archive -@
        if [[ $? != 0 ]];
            then
                echo "Error creating zip"
                exit 1
        fi
    done
EOF

./ziper.sh

In oneliner use break

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement