0

I have code that opens a bash file in a terminal for entering the sudo password:

test "$IN_TERM" || {
    export IN_TERM=1
    konsole -e "$0"
    exit 0
} && true

I need to convert it to a form with if fi tags. I tried this option, but then an infinite number of terminals open:

if [[ -n $IN_TERM ]]; then  
    export IN_TERM=1  
    else  
    konsole -e "$0"  
    exit 0
fi

Thanks.

1 Answer 1

2

I think the most direct way to convert your code is:

if ! test "$IN_TERM"; then
    export IN_TERM=1
    konsole -e "$0"
    exit 0
fi

You can then rewrite it as

if ! [[ "$IN_TERM" ]]; then
    export IN_TERM=1
    konsole -e "$0"
    exit 0
fi

or

if [[ ! "$IN_TERM" ]]; then
    export IN_TERM=1
    konsole -e "$0"
    exit 0
fi

or

if [[ -z "$IN_TERM" ]]; then
    export IN_TERM=1
    konsole -e "$0"
    exit 0
fi
7
  • The thing is that I'm trying to get rid of test completely in code. I need to do something with if [[ -n $IN_TERM ]]; then ...
    – moninah
    Commented Nov 29, 2023 at 12:28
  • 1
    @moninah What’s the point exactly? At least with bash, test is a shell buil-in, just like [[. Anyway, I just added a few rewrites, with [[ instead of test. Commented Nov 29, 2023 at 13:25
  • 1
    @moninah "I'm trying to get rid of test completely in code" – test … is exactly equivalent to [ … ]. [[ is somewhat different. Any of the three can be used after if or without if. So what is the point? Commented Nov 29, 2023 at 13:27
  • @moninah If you just need to get rid of the test command, you might also simply rewrite your initial code as [[ -n $IN_TERM ]] || { … } && true. BTW, the && true part looks useless. Commented Nov 29, 2023 at 13:28
  • 2
    @user2233709 Technically in Bash [[ is not a builtin, it's a keyword and this fact has consequences. See this answer. Commented Nov 29, 2023 at 13:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .