2

Suppose I have a file format I want to save database backups to given as such:

echo "~/backups/$(date +'%Y-%m-%d_%H-%M-%S').sql"

Now how can I specify this result as a filename for output in shell?

mysqldump my_db > ....?

By the way: shell interprets the result of a nested echo command as an executable command/file. So    It would seem that:

 mysqldump my_db > $(echo "something")

does NOT work. Instead, shell looks for a file called something and tries executing it?

Blake Regalia
  • 2,677
  • 2
  • 20
  • 29

3 Answers3

5

There is no need to use nested echo. You can avoid it:

mysqldump my_db > ~/backups/$(date +'%Y-%m-%d_%H-%M-%S').sql
anubhava
  • 761,203
  • 64
  • 569
  • 643
-1

$(echo "something") is not the problem, while ~ is. It works fine if you use full path:

echo 'hello world' > $(echo "/home/root/backups/$(date +'%Y-%m-%d_%H-%M-%S').sql")

In case you're interested in how to use ~:

eval "echo 'hello world' > $(echo "~/backups/$(date +'%Y-%m-%d_%H-%M-%S').sql")"
Batcher
  • 167
  • 1
  • 1
    Not really... bash redirect can handle `~`; no need to convert `~` to `/home/root/`; unless, it is being run by some other user or from a non-interactive way... – anishsane Apr 01 '13 at 06:38
  • Really don't perpetrate [useless use of `echo`](http://www.iki.fi/era/unix/award.html#echo) – tripleee Jan 06 '19 at 08:38
-1

I think there are more possibilities to answer this question: How to name a file with current time? [duplicate]

--

You can create a file in bash by using different utilities

Using touch

root@ubuntu:~/T/e/s/t# touch $(date +"%T") //you can format time as per your need 

Using editor

root@ubuntu:~/T/e/s/t# vi $(date +"%T") 

Using redirection

root@ubuntu:~/T/e/s/t# echo "Input for file" > $(date +"%T")

Time format

In place of %T you can use your own time format Refer: http://man7.org/linux/man-pages/man1/time.1.html

Mohit Rathore
  • 428
  • 3
  • 10
  • The question asks specifically how to redirect. The parts of this answer which do not duplicate the accepted answer are simply not pertinent here. – tripleee Jan 06 '19 at 08:37
  • I specifically mentioned this question in the headline: How to name a file with current time? [duplicate] Because you mentioned the question as a duplicate of this one and I'm not able to comment on that page. – Mohit Rathore Jan 06 '19 at 08:54