1

I'm trying to learn how to use the signal trap command on Bash. The trap command is quite easy to use, but the issue that hangs in my head is the importance of using single and double quotes.

  • What is the difference between the single and double quotes used with the trap command ?

  • Can you give a few simple examples that clearly show the difference between the two uses ?

6
  • 3
    There's nothing special about the trap command wrt. single or double quotes. If in doubt, use a function: deb(){ echo "' ${BASH_COMMAND[@]}"; }; trap deb DEBUG Commented Dec 31, 2019 at 12:27
  • Actually, it was the article here that confused me. Thx your reply @mosvy Commented Dec 31, 2019 at 12:35
  • Please give example. And narrow down, where in the article. Commented Dec 31, 2019 at 13:50
  • @ctrl-alt-delor In the "Cleaning Up Temporary Files" Commented Dec 31, 2019 at 14:03
  • Please give example. And narrow down, where in the article. By editing question, to include an example and a quote (and reference) from the article. Commented Dec 31, 2019 at 17:10

1 Answer 1

4

The trap command just takes string to be processed as shell commands, like eval. That string will be processed for expansions, so the difference between double and single quotes is when the first expansions happen. In double-quotes, they happen when the trap is set, in single quotes when it triggers.

E.g. this will print foo=1 when the read is interrupted, but with single quotes it would print foo=2:

#!/bin/bash foo=1 trap "echo foo=$foo; exit" INT foo=2 read # hit Ctrl-C here 

Of course, even with double quotes, the resulting command gets expanded also when the trap triggers, so having foo=$0 on the line before the trap above, would result in the script printing the script's name on interrupt.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.