0

I am writing a shell script that takes argument $1 as a destination directory and $2 as a source directory. Script:

#!/bin/zsh
# readlink is used to get absolute path when relative path is provided
output_path=`readlink -f "${1:-.}"`
src_dir=`readlink -f -- "${2:-~/Downloads}"`
echo "destination dir: $output_path"
echo "source dir: $src_dir"
return

Output:

destination dir: /home/ashwin
source dir: 

I get blank in source directory variable. Changing the default value of src_dir to the absolute path of folder solves the problem. Script:

#!/bin/zsh
# readlink is used to get absolute path when relative path is provided
output_path=`readlink -f "${1:-.}"`
src_dir=`readlink -f -- "${2:-/home/ashwin/Downloads}"`
echo "destination dir: $output_path"
echo "source dir: $src_dir"
return

Output:

destination dir: /home/ashwin
source dir: /home/ashwin/Downloads

Also providing ~/Downloads as an argument to script works fine. I want to understand the reason why ~/Downloads as the default value of src_dir does not work.

TryToSolveItSimple
  • 873
  • 1
  • 12
  • 23

1 Answers1

0

I want to understand the reason why ~/Downloads as the default value of src_dir does not work.

From bash manual tilde expansion:

If a word begins with an unquoted tilde character (‘~’), ...

The "${2:-~/Downloads}" doesn't begin with an unquoted tilde character. And the result ~/Downloads is quoted within double ". The ~ is not expanded. So readlink -f -- "~/Downloads" is run. Because the path named literally /home/ashwin/~/Downloads doesn't exists on your system, readlink generates no output and exits with a nonzero exit status (1 on my system).

Please do not use backticks `. Use $( ) instead.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • `Please do not use backticks. Use $( ) instead.` Is this related to ~ expansion or a general observation? Can you please explain why $( ) is preferable to `? – Ashwin Mahantha Apr 03 '20 at 01:31
  • General [bash hackers wiki deprecated and obsolete syntax](https://wiki-dev.bash-hackers.org/scripting/obsolete). – KamilCuk Apr 03 '20 at 01:32