1

I'm writing a script where I have a default directory for outputting data or the user can specify a directory. The problem is, I don't know how to do this eloquently. Here is what I have:

#!/bin/bash

OUTPUT="$1"

DEFAULT_DIR=/Default/Dir/For/Me

if [ -z "$OUTPUT" ] 
then
   OUTPUT=.${DEFAULT_DIR}
else
   OUTPUT=""${OUTPUT_DIR}""${DEFAULT_DIR}""
fi

echo "$OUTPUT"
  • If I do this ./script / I get //Default/Dir/For/Me

  • If I do this ./script /home I get /home/Default/Dir/For/Me

  • If I do this ./script /home/ I get /home//Default/Dir/For/Me

Is there any way to make this pretty and handle the first scenario properly? Obviously, the first scenario won't work because the directory // does not exist.

4

2 回答 2

3

(只是为了从评论中弄清楚)

我的建议是通过管道tr -s "/"删除重复的斜杠:

$ echo "/home//Default/Dir/For/Me" | tr -s "/"
/home/Default/Dir/For/Me
$ echo "/home//Default/Dir/For/M//////////e" | tr -s "/"
/home/Default/Dir/For/M/e
于 2013-06-28T15:38:05.687 回答
2

这是另一个解决方案,无需分叉另一个进程:

DEFAULT_DIR=${DEFAULT_DIR//\/\///}

这将替换字符串中所有出现的//with /

于 2013-06-28T17:03:10.800 回答