Sindhu S
Sindhu S

Reputation: 1012

How to pass a variable to a command line program?

I want to create files with the current date as prefix and some string as the remaining part of the filename.

Something like this:

touch `date +"%Y-%m-%d-"$1`.md hello

where $1 should pick up hello and create me a file called 2014-3-3-Hello.md.

Upvotes: 1

Views: 144

Answers (2)

jub0bs
jub0bs

Reputation: 66344

For convenience, you may want to define a custom function (called touchdatemd below) for that:

$ touchdatemd () { touch $(date +"%Y-%m-%d-")"$1".md; }

Test:

$ mkdir test && cd test
$ touchdatemd hello
$ touchdatemd "I love pie"
$ touchdatemd bye
$ ls
2014-12-28-bye.md   2014-12-28-I love pie.md    2014-12-28-hello.md

Upvotes: 4

You can use command substitution:

touch "$(date +"%Y-%m-%d-")hello.md"

If you want to name a number of files, all ending with .md, just wrap the thing in a for loop:

for baseName in hello world foo bar ; do
    touch "$(date +"%Y-%m-%d-")$baseName.md"
done

That will create four files with names like 2014-3-3-hello.md, 2014-3-3-world.md, etc.

Upvotes: 5

Related Questions