Reputation: 1693
I thought I could figure this out. I've written more complex shell scripts before, so I thought it'd be easy to do. I've wasted an hour now and tearing my hair out because nothing I do works and I cannot find any usable help online.
All I want to do is the equivalent to this simple little C# code snippet here:
var splat = "some/path";
if (!splat.StartsWith("/"))
{
splat = $"/{splat}";
}
Take a string argument. If it starts with a slash, do nothing. If it doesn't start with a slash, add it to the front of the string variable.
How do I accomplish this apparent herculean task in a bash script?
My attempt:
#!/bin/bash
dir="/root/home"
sub_dir=$1
echo "argument given: '"$sub_dir"'"
if [ ! -z $sub_dir ]
then
echo "before: "$dir$1
if [[ "${sub_dir}" != *'/' ]]; then
echo "starts with slash!"
else
echo "doesn't start with slash!"
$sub_dir="\/"${sub_dir}
echo "slash added: "$sub_dir
fi
else
echo "argument not given"
echo $dir
fi
echo "$dir$sub_dir"
I have also tried using regex with no success for the conditional:
if [[ "$HOST" =~ ^user.* ]]; then
I also have not found a way to pass an argument that does start with a slash or create a string that starts with a slash without it for some reason treating it as a file path instead of a string (and subsequently resulting in an error).
EDIT: bash --version
says it's GNU bash verison 5.0.17, if that makes any difference.
Upvotes: 1
Views: 556
Reputation: 50750
Use a parameter expansion that removes the leading character if it is a slash or leaves the value intact otherwise, and prepend the result with a slash.
$ s1=some/path s2=/some/path
$ echo /${s1#/}
/some/path
$ echo /${s2#/}
/some/path
Simply put, you can replace that if command with this line:
sub_dir=/${sub_dir#/}
Upvotes: 4
Reputation: 940
#!/bin/bash
dir="/root/home"
sub_dir=$1
echo "argument given: '"$sub_dir"'"
if [ ! -z $sub_dir ]
then
echo "before: "$dir$1
if [[ $sub_dir = '/'* ]]; then
echo "Start with slash"
else
echo "doesn't start with slash!"
slash="/"
sub_dir="${slash}${sub_dir}"
echo "slash added: "$sub_dir
fi
else
echo "argument not given"
# echo $dir
fi
echo "$dir$sub_dir"
Upvotes: 2