sorin
sorin

Reputation: 170498

How to temporary disable bash trace mode before sourcing another script and restore after?

I need to source some external scripts in bash but I want to avoid displaying the trace output when doing so (set -x).

The current trace status is unknown so I need to restore it after running the source command.

# save xtrace status
set +x
source ~/.credentials
# restore xtrace status

I cannot use subshells because I would not be able to use the variables defined by the sourced script.

How can I do this in a chean and portable way?

Upvotes: 2

Views: 1274

Answers (1)

Nahuel Fouilleul
Nahuel Fouilleul

Reputation: 19315

the special variable $- contains the current set flags.

[[ $- = *x* ]] && old_set_x=1

# disable -x
set +x

# do something

# restore if necessary
((old_set_x)) && set -x

Upvotes: 3

Related Questions