Verbose word Bash Script Arguments passed to a separate screen
I am trying to use a very small bash script to send commands to a separate screen on Linux.
The screen is currently off and I can send commands to the screen using the bash script below.
#!/bin/bash
COMMAND=$1;
screen -S "detachedscreen" -X stuff $COMMAND`echo -ne '\015'`
The problem occurs when the argument contains more than one word.
Adding single quotes or double quotes around the argument does not solve the problem.
When multiple word arguments are sent to a separate screen, it throws the following error.
-X: STUFF: invalid option firstArgument
How can I send multiple word arguments to bash without throwing this error?
Your question is unclear, but it looks like your arguments should be properly separated. If they are shell commands, you can use a semicolon as well as a newline. If the receiving program requires newline-separated input, then first of all you need to do the correct quoting in your script:
#!/bin/bash
COMMAND=$1;
screen -S "detachedscreen" -X stuff "$COMMAND"`echo -ne '\015'`
which can also be refactored to accept multiple arguments:
#!/bin/bash
screen -S "detachedscreen" -X stuff "$@"$'\015'
and of course you need to pass the commands separated by newline like
yourscript "hello
buy
more
beans"
If you want your script to always insert a newline between arguments, you can say
yourscript hello buy more beans
you can also do this:
#!/bin/bash
commands=$(printf '%s\n' "$@")
screen -S "detachedscreen" -X stuff "$commands"$'\015'
If every command should have a DOS carriage return, try
#!/bin/bash
commands=$(printf '%s\r\n' "$@")
screen -S "detachedscreen" -X stuff "$commands"
Now if you want a string with spaces in it, just specify it
yourcommand hello "buy more beans"
will send hello
, then buy more beans
on one line.
source to share