Escaping parameter to bash function [duplicate] - bash

This question already has answers here:
What does $# mean in a shell script?
(8 answers)
Closed 6 years ago.
First I'll describe the problem. I often copy files from my linux desktop to my android tablet. For reasons I'd rather not go into, the easiest way I found to do this is by running sshDroid (a ssh server) on my tablet, and using scp from the shell to copy files over. The scp command takes the following form:
scp -P 2222 ./some\ document\:\ with\ subtitle\ -\ author.txt \
root#197.157.0.211:/sdcard/uploads
The only thing that changes in this expression is the name of the file, and that is quite easily attained via tab-completion. Not even the ip address changes. Since I upload files quite often, I would very much like to not type the same characters over and over again. To this end I thought I would write a shell function and append it to .bashrc. The function I wrote is as follows:
upload(){ scp -P 2222 $# root#192.168.0.151:/sdcard/uploads; }
it's usage is supposed to be:
upload ./some\ document\:\ with\ subtitle\ -\ author.txt
but when I try it I get the following output:
SSHDroid
Use 'root' as username
Default password is 'admin'
root#192.168.0.151's password:
./some: No such file or directory
ssh: Could not resolve hostname document: Name or service not known
with: No such file or directory
subtitle: No such file or directory
-: No such file or directory
author.txt: No such file or directory
It looks like bash is automatically unescaping the filename before it passes it to the function, and the scp command treats it as multiple filenames due to the spaces in the name.
My question is: How do I preserve the backslashes in the parameter, or failing that how do I reescape it within the function? After fiddling with this for a while I'm sorely tempted to write a simple python script and drop it into /usr/local/bin. Is there some other bash-native solution that I'm missing?

Quotes!
Unquoted, $# behaves identically to $*; if you want to preserve original tokenization, you need to use "$#" instead. Thus:
upload() { scp -P 2222 "$#" root#192.168.0.151:/sdcard/uploads; }

Related

Backup alias in Bash Profile [duplicate]

This question already has answers here:
Make a Bash alias that takes a parameter?
(24 answers)
Closed 4 months ago.
I am trying to create an alias in my bash profile such that I can call
backup_dir Playground
and have it complete:
cp -r Playground $HOME/BACKUP
I would also like to ensure that if the file/directory is of the same name it is just overwritten.
The code I input in my bash_profile is as follows:
alias backup='cp $2 $HOME/BACKUP/$2'
alias backup_dir='cp -r $2 $HOME/BACKUP/$2'
I also tried it with $1 but it did not work either.
What actually occurs is that it copies the contents of my backup directory and creates it in the directory I'm supposed to be copying/copying from.
Aliases don't really take arguments, and trying to define aliases as if they did winds up in strange territory (if you define a simple alias 'foo' that just echos instead of copies, you'll find it reversed the order of the arguments you passed - i.e. the first argument is the backup directory and the second is the directory you wanted.) I'm guessing the details of why that happens aren't super interesting to you - but that is... 'expected'.
The solution is to write a function to use in your alias, or to write a small shell script and call that instead.
Aliases really substitute 'bash' as the command that then executes the string you pass (if you echo $0 instead of $1, you'll see something like 'bash foo' as the output).
More detailed instructions can be found in the ubuntu forums (for example)

Bash Shell Script Issues

I am new to UNIX and have a homework assignment that is giving me trouble. I am to write a script that will back up specified files from the current directory into a specified destination directory. This script is to take three arguments.
sourcePath, which is the path to the source files/files being backed up or copied.
backupPath, which is the path to the target directory where the files will be backed up.
filePrefix, which is used to identify which files to backup, specifically only files whose names begin with the given prefix will be copied while others will be ignored. Example would be, if the user enters the letter "d", then all files starting with that letter are to be copied while any other file is to be ignored.
I haven't learned much about scripting/functions in bash so I've tried looking up tutorials which have been helpful but not enough. This script is something I can easily do when just typing out the commands. For instance, I would cd into the target directory that has the files, then using the cp command copy files that begin with the specific prefix to the target directory, but when making a script I am at a dead end.
I feel as though my code is monumentally incorrect and its due to my lack of experience, but nothing online has been of any help. So far my code is
read sourcePath
read backupPath
read filePrefix
grep /export/home/public/"$sourcePath
mkdir -p $backupPath
cp /export/home/public/"$sourcePath"/$filePrefix /home/public/"$backupPath"
So an example execution of the script would be
$ ./script.sh
(sourcePath)HW4testdir (backupPath)backup (filePrefix)d
Output:
backing up: def (example file starting with d)
backing up: dog (example file starting with d)
So far when executing the code, nothing happens. Again, I'm sure most, or even all of the code is wrong and totally off base, but I never learned about scripting. If I did not have to create a script, I could easily achieve this desired outcome.
I suggest with bash:
read -r -p "sourcePath: " sourcePath
read -r -p "backupPath: " backupPath
read -r -p "filePrefix: " filePrefix
mkdir -p /home/public/"$backupPath"
cp /export/home/public/"$sourcePath/$filePrefix"* /home/public/"$backupPath"
Make sure that the used user has the right to create the directory /home/public/"$backupPath".
See: help read
For a start: Your assignment states, that your script should accept arguments.
However your script does not take arguments. It reads the parameters from standard input. Arguments are passed to the script on the command line, and your script would be called as
./script.sh HW4testdir backup d
Hence you can't use read to fetch them. The first argument is available under the name $1, the second argument is $2 and so on. You could write for instance
sourcePath=${1?Parameter missing}
which has the side effect to abort the script with an error message, if the caller forgets to pass the parameter.
Another point: You don't say anywhere that bash should be used to run the script. Since you want the script to be called by
./script.sh ....
and not by
bash ./script.sh ....
you must encode the information, that bash should be used, in your script. Assuming that your bash is located in /usr/bin, you would do this by making the first line of the script
#!/usr/bin/bash

bash script doesn't find mkdir [duplicate]

This question already has answers here:
Getting "command not found" error in bash script
(6 answers)
Closed 2 years ago.
I've created a simple script to check if a folder exists and if not to create it. The script that follow
#!/bin/bash
PATH=~/Dropbox/Web_Development/
FOLDER=Test
if [ ! -d $PATH$FOLDER ]
then
echo $PATH$FOLDER 'not exists'
/bin/mkdir $PATH$FOLDER
echo $PATH$FOLDER 'has been created'
fi
works only if the mkdir command is preceded by /bin/. Failing in that, bash env output the error message "command cannot be found".
I though this could have been related to the system $PATH variable, but it looks regular (to me) and the output is as following:
/Library/Frameworks/Python.framework/Versions/2.7/bin:/bin:/usr/local/bin:/usr/bin:/sbin:/usr/local/sbin:/usr/sbin
I'm not sure whether the order with the different bin folders have been listed make any difference, but the /bin one (where the mkdir on my OSX Maverick) seems to reside is there hence I would expect bash to being able to execute this.
In fact, if I call the bash command from terminal, by typing just mkdir bash output the help string to suggest me how the mkdir command should be used. This suggests me that at a first instance bash is able to recognise the $PATH variable.
So what could be the cause? Is there any relation between the opening statement at the top of my .sh - #!/bin/bash - file and the "default" folder?
Thanks
Yeah, sometimes it is a bad idea to use capital letters for constant variables, because there are some default ones using the same convention. You can see some of the default variables here (Scroll to Special Parameters and Variables section). So it is better to use long names if you don't want to get any clashes.
Another thing to note is that you're trying to replicate mkdir -p functionality, which creates a folder if it does not exist (also it does create all of the parents, which is what you need in most cases)
One more thing - you always have to quote variables, otherwise they get expanded. This may lead to some serious problems. Imagine that
fileToRemove='*'
rm $fileToRemove
This code will remove all files in the current folder, not a file named * as you might expect.
One more thing, you should separate path from a folder with /. Like this "$MY_PATH/$MY_FOLDER". That should be done in case you forget to include / character in your path variable. It does not hurt to have two slashes, that means that /home/////////user/// folder is exactly the same /home/user/ folder.
Sometimes it is tricky to get ~ working, so using $HOME is a bit safer and more readable anyway.
So here is your modified script:
#!/bin/bash
MY_PATH="$HOME/Dropbox/Web_Development/"
MY_FOLDER='Test'
mkdir -p "$MY_PATH/$MY_FOLDER"
The problem is that your script sets PATH to a single directory, and that single directory does not contain a program called mkdir.
Do not use PATH as the name of a variable (use it to list the directories to be searched for commands).
Do learn the list of standard environment variable names and those specific to the shell you use (e.g. bash shell variables). Or use a simple heuristic: reserved names are in upper-case, so use lower-case names for variables local to a script. (Most environment variables are in upper-case — standard or not standard.)
And you can simply ensure that the directory exists by using:
mkdir -p ~/Dropbox/Web_Development
If it already exists, no harm is done. If it does not exist, it is created, and any other directories needed on the path to the directory (eg ~/Dropbox) is also created if that is missing.

variable in scp filename not working?

I'm trying to scp a backup tgz file from one server to another every night. The backup script uses the following $date var just fine but when I modify it slightly for scp it breaks:
#!/bin/sh
date=`date +%Y-%m-%d`
rbfile=`/backups/$date_00h00.tgz`
scp $rbfile user#myserverip:
But the script dies with the error:
/backups/.tgz: No such file or directory
On a side note, I really should switch to rsync for better remote backups - the tgz files are at 3.5GB now. Any recommended tutorials?
when using $date_00h00 you tell bash to use the variable named date_00h00, because letters, numbers and _ characters are allowed as variables names.
Enclose the variable name in {} and it will correct the problem :
rbfile=`/backups/${date}_00h00.tgz`

Using a filename with spaces with scp and chmod in bash

Periodically, I like to put files in the /tmp directory of my webserver to share out. What is annoying is that I must set the permissions whenever I scp the files. Following the advice from another question I've written a script which copies the file over, sets the permissions and then prints the URL:
#!/bin/bash
scp "$1" SERVER:"/var/www/tmp/$1"
ssh SERVER chmod 644 "/var/www/tmp/$1"
echo "URL is: http://SERVER/tmp/$1"
When I replace SERVER with my actual host, everything works as expected...until I execute the script with an argument including spaces. Although I suspect the solution might be to use $# I've not yet figured out how to get a spaced filename to work.
It turns out that what is needed is to escape the path which will be sent to the remote server. Bash thinks the quotes in SERVER:"/var/www/tmp/$1" are related to the $1 and removes them from the final output. If I try to run:
tmp-scp.sh Screen\ shot\ 2010-02-18\ at\ 9.38.35\ AM.png
Echoing we see it is trying to execute:
scp SERVER:/var/www/tmp/Screen shot 2010-02-18 at 9.38.35 AM.png
If instead the quotes are escaped literals then the scp command looks more like you'd expect:
scp SERVER:"/var/www/tmp/Screen shot 2010-02-18 at 9.38.35 AM.png"
With the addition of some code to truncate the path the final script becomes:
#!/bin/bash
# strip path
filename=${1##*/}
fullpath="$1"
scp "$fullpath" SERVER:\"/var/www/tmp/"$filename"\"
echo SERVER:\"/var/www/tmp/"$filename"\"
ssh SERVER chmod 644 \"/var/www/tmp/"$filename"\"
echo "URL is: http://SERVER/tmp/$filename"
The script looks right. My guess is that you need to quote the filename when you pass it into your script:
scp-chmod.sh "filename with spaces"
Or escape the spaces:
scp-chmod.sh filename\ with\ spaces
the easier way without worrying about spaces in file names, (besides quoting) is to rename your files to get rid of spaces before transferring. Or when you create the files, don't use spaces. You can make this your "best practice" whenever you name your files.

Resources