Skip to content
Advertisement

Terminal closes when I source my script (run with dot at the start)

Here is my code:

#!/bin/bash 
if [[ $1 = "" ]]; then
    exit 0
fi
array=($(cat $1))
let b=${#array[@]}-1
count=0
for i in {1..7}; do
    for j in {30..37}; do
        for n in {40..47}; do
            if [[ $count -gt $b ]]; then
                printf 'n'
                printf 'e[0m'
                exit 1
            fi
            printf 'e[%s;%s;%sm%-5s' "$i" "$j" "$n" "${array[$count]}"
            printf 'e[0m'
            let count=$count+1
        done
        printf 'n'
    done
done
#printf 'n'
printf 'e[0m'
exit 0

The problem is that when I start it like this

. color.sh arg

or without argument, it just closes. I know that the reason for that is exit. Is there any way correct my code so I could start a script with dot at start and terminal wouldn’t close after execution? I don’t want to start it like this: ./script

Advertisement

Answer

Replace all exit with return. return inside a sourced script will even work with exit codes:

$ . <(echo "echo before; return 0; echo after")
before
$ echo $?
0
$ . <(echo "echo before; return 7; echo after")
before
$ echo $?
7
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement