Maxthecat
Maxthecat

Reputation: 1328

How can I pass in string quotes in bash script?

On the command line, if I type

adb -s "" shell

I get a shell, but if I try to do this in bash:

#!/bin/bash
ADB_ID=""
adb -s ${ADB_ID} shell

I get an error. I understand that it's not passing in any content for ${ADB_ID}. I've tried escaping the quotes, which results in it looking for the device named "", which is incorrect. I've also tried using single quotes and single escaped quotes, which are both wrong. How can I pass the command line equivalent in my bash script?

Upvotes: 1

Views: 748

Answers (2)

glenn jackman
glenn jackman

Reputation: 247192

Get into the habit of using double quotes around your variables, (almost) always:

adb -s "$ADB_ID" shell

is what you want.

Quoting is shell programming is a much-discussed topic. I won't get into the details here except to say:

  • the shell uses does certain expansions, including variable expansion, before it tokenizes the line into words: the command and its parameters.
  • the shell uses sequences of whitespace to separate words
  • if you don't quote the variable above, the shell will see this:

    adb -s  shell
    

    and it has no way to know that there should be something between "-s" and "shell".
    With quotes, the shell sees

    adb -s "" shell
    

    and it is obvious that there is a zero-length word there.

For more research, https://stackoverflow.com/tags/bash/info is a good place to start.

For this specific issue, BashPitfalls numbers 2 through 5.

Upvotes: 6

wjandrea
wjandrea

Reputation: 33159

Always quote variables, unless you know exactly what you're doing.

adb -s "$ADB_ID" shell

The shell expands variables then collects the command line arguments, so if there's an unquoted null variable ($ADB_ID), it gets ignored. When you quote a null variable ("$ADB_ID"), that's the same as passing a null string as an argument.

Upvotes: 0

Related Questions