0

Sorry if this is poorly worded as I am new to shell script.

I'm trying to write a script and I want to take in args such as the unix date command does.

Example:

$ date '+%I:%M %p'
08:45 PM

So how would I do something like this in my script?


EDIT: What I'm trying to do in my script is pass arguments in the same fashion as the date command.

So if my script were to change all %a arguments to foo, it would do the following:

$ ./myscript '%a bar'
foo bar
Micah Cowell
  • 392
  • 4
  • 18
  • 1
    This isn't something you want to do in bash. – Ignacio Vazquez-Abrams Apr 27 '16 at 03:50
  • 1
    Is it the function of date you wish to emulate or just basic command line parameter passing? Check out the [GNU Bash Reference Manual](https://www.gnu.org/software/bash/manual/) and check out `$*`, `$@` etc for information on the latter. – Greg Tarsa Apr 27 '16 at 03:52
  • This is actually quite complicated, they're parsing the actual argument which is much harder than passing arguments into the script itself. Do you want to parse strings like this... '+%I:%M %p'? – Harry Apr 27 '16 at 03:54
  • Something, *anything*, with better text processing. – Ignacio Vazquez-Abrams Apr 27 '16 at 04:07
  • 1
    `myscript () { echo "${1//%a/foo}"; }` – tripleee Apr 27 '16 at 05:10
  • The better way is to use C. The date command can easy handle its arguments since it implemented in C. You can refer it from [here][1]. [1]: http://git.savannah.gnu.org/cgit/coreutils.git/tree/src/date.c – shafeeq Apr 27 '16 at 05:25
  • Here is what you can do with `bash` arguments: http://stackoverflow.com/questions/192249/how-do-i-parse-command-line-arguments-in-bash – J. Chomel Apr 27 '16 at 08:21
  • Thanks @tripleee your solution works great. It does seem that it would be best to do this sort of thing in some other programming language though. Thanks everyone for all the help. – Micah Cowell Apr 30 '16 at 07:45

1 Answers1

1

Thanks to @tripleee I was able to come up with a solution that allows you to substitute multiple keywords in a string arg.

Here's the code:

res="${1}"
res="${res//"%a"/water}"
res="${res//"%b"/chocolate}"
echo "$res"

Input:

./myscript "like %a for %b"

Output:

like water for chocolate

This method goes through every keyword you want to replace in the arg even if it isn't in there so it's not very efficient but it gets the job done.

Community
  • 1
  • 1
Micah Cowell
  • 392
  • 4
  • 18
  • You want to double the first slash, for global substitution. With one slash, only the first occurrence will be substituted. – tripleee Apr 30 '16 at 10:19
  • I would expect this to be faster than an external command, even for dozens of substitutions. – tripleee Apr 30 '16 at 10:21