0

I'm not sure if this question has been asked or answered. If it has, I apologize. I wasn't too sure what to look for, but I'm writing a bash script to take in a path from the user, my script works with absolute and relative paths. But I was wondering if there was a way to interpret the shorthand notation to these paths. For example ~/ for home or . for current or ../ for a directory up. I was having a bit of trouble figuring this out. Here is my current bash script for reference.

#!/bin/bash

echo "What is the path you'd like me to search?"

read PASSED

while [ ! -d $PASSED ]; do
    echo "$PASSED is not a valid directory"
    echo "Please provide a valid Path"
    read PASSED
done

ls -l $PASSED | awk -v user=`whoami` '{ if($3 == user){print $0}}'
Camilo
  • 85
  • 8
  • Could you clarify your desire, i.e. "a way to interpret the shorthand notation to these paths"? What exactly do you want to do? – djkern Apr 25 '18 at 22:58
  • I want to be able to pass ~/some/path or ../some/path and have my script interpret it properly as a path. Because as of right now, it doesn't understand ~/some/path as a path – Camilo Apr 25 '18 at 22:59
  • 1
    `..` is an actual filename that you can access directly. `~` is shell syntax, which you'll have to add support for – that other guy Apr 25 '18 at 23:05
  • What would be a good approach to adding support for ~/ ? – Camilo Apr 25 '18 at 23:12

1 Answers1

1

. and .. are not shortcuts, they're actual directory names that exist in every directory. You don't need to do anything to support this.

~, however, is bash syntax that you can emulate.

In the simplest case, just check for a leading ~ and replace:

# Read some path
printf 'Enter a path: '
IFS='' read -r mypath

# If the path starts with ~, replace it with $HOME
[[ $mypath = '~'* ]] && mypath="$HOME${mypath#'~'}"

# Show what we got
echo "The path is $mypath, aka $(realpath "$mypath")"

Note that this does not support the various other ~ syntaxes like ~username or ~+

that other guy
  • 116,971
  • 11
  • 170
  • 194