0

When I'm debugging a script, I'll often take a line I'm not quite sure about e.g.:

hdiutil create -srcfolder "$3" -format UDRO -fs APFS -volname "$1" -ov "$2"

and simply change it to:

echo hdiutil create -srcfolder "$3" -format UDRO -fs APFS -volname "$1" -ov "$2"

Then when I run my script the first time, it won't run the (potentially incorrect) command but I can see it and check that it looks correct… and maybe even copy/paste it to run it manually.

But this isn't reliable/correct if any of the arguments have spaces in them. The echo shows spaces within an argument just the same as the separator between arguments.

I found the set -x command which helpfully logs every command with arguments properly escaped! That's what I'm using for now, but it's pretty broad-grained (noisy across a large script where I'm focused on just one line) and doesn't prevent the actual un-verified command from running.

Is there a quick/clean way to do this for just one line. Or some other trick using commonly available commands — maybe some combination of env and printf or whatnot? or a dedicated command that got included for basically this purpose?

Ideally it'd be something I could just pre-pend to the line in question which would both "comment it out" and show me exactly what it would have done if enabled.

2
  • You can do set -x right before the line you're interested in, and set +x after. Commented Jun 15, 2018 at 17:21
  • If you want a more comprehensive debugging solution than set -x then you could use bashdb which can be installed via MacPorts or Homebrew. Commented Jun 15, 2018 at 17:37

1 Answer 1

1

You can use printf %q:

#!/bin/bash
run() {
  printf "%q " "$@"  # show each argument shell escaped
  printf '\n'
  (( dryrun )) || "$@" # optionally run the command
}

dryrun=1
run hdiutil create -srcfolder "$3" -format UDRO -fs APFS -volname "$1" -ov "$2"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.