0

I am looking for a way to pass a argument to bash script with backslash.

I thought it will be convenient to send a file from my PC to server with a single drag and drop.
I am using windows terminal to get access to the server, and file explorer can copy file path with drag and drop. So I wrote a script like below.

#!/bin/bash

ID=user
PC_IP=xxx.xxx.xxx.xxx
PC_PORT=xxx

FILEPATH=@1

scp -P $PC_PORT -r $ID@$PC_IP:$FILEPATH .

The only problem is file path copied from file explorer contains backslash. So I want to pass whole file path as string argument.
I tried to find passing argument with special character, but everyone said to use single quote or escaping. I think it is bothering to type quote every single time.
Is there any way to pass backslash without quote or escaping?

jhy
  • 13
  • 3
  • you may only need dbl-quotes surrounding your variables in your script to make this work BUT you have other syntax problems for `bash` script, copy/paste your code into https://shellcheck.net and fix problems identified there. Hint, `FILEPATH="$1"` may solve your problem. Good luck. – shellter Jul 14 '21 at 04:20

1 Answers1

0

(I don't have a Windows setup to test with, but assuming it just fills in the raw path when you drag-and-drop files, what I suggest here should work.)

Everything entered on a shell command line -- including arguments to your script -- need to conform to shell syntax, which assigns special meaning to backslashes, spaces, and a bunch of other characters you might find in a Windows file path. In order to be passed through to the script as literal characters, they must be quoted or escaped as per the rules of shell syntax.

But there is another way... Rather than passing the file path as an argument, you could have the script read it as input after you start the script. Since the script would be reading it directly, the script can control what syntax is or isn't needed. In particular, it can use read -r, where the -r means "raw mode", which doesn't mess with backslashes. Something like this:

#!/bin/bash

id=user
pc_ip=xxx.xxx.xxx.xxx
pc_port=xxx

read -r -p "File: " filepath

scp -P "$pc_port" -r "$id@$pc_ip:$filepath" .

Note that I also switched to lowercase variable names (lower- and mixed-case variable names are safer, because a bunch of all-caps names have special meanings that can cause trouble). I also double-quoted all the variable references, to avoid weird parsing of spaces and maybe other things (you should almost always do this).

You could also make the script accept either a command-line argument (which would have to be quoted/escaped) or if that's not supplied, take it as input instead:

...
if [[ -n "$1" ]]; then
    filepath=$1
else
    read -r -p "File: " filepath
fi
...
Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151