johnn1e
johnn1e

Reputation: 55

Shell variables in Google Colab Console

I'm using Google Colab and I want to save this two files to my Drive with today's date, this doesn't seem to work. How can I workaround this?

Input

!read -p "Please enter today's date: " d
!cp f1_${d}.csv "drive/My Drive"
!cp f2_${d}.csv "drive/My Drive"

Output

Please enter today's date: 08-01-21
cp: cannot stat 'f1_/bin/bash8-01-21.csv': No such file or directory
cp: cannot stat 'f2_/bin/bash8-01-21.csv': No such file or directory

I want the output files to be f1_08-01-21.csv and f2_08-01-21.csv.

Upvotes: 4

Views: 1477

Answers (1)

tripleee
tripleee

Reputation: 189749

The reason this doesn't work is that each !command runs in a separate subshell. The read -p runs, then exits, and the variable it read is no longer available, similarly to what would happen if you closed and reopened a notebook and tried to evaluate code blocks which depend on earlier code blocks you have not evaluated after restarting.

You don't need to input today's date manually anyway; your computer already knows.

!cp "f1_$(date +%F).csv" "drive/My Drive"
!cp "f2_$(date +%F).csv" "drive/My Drive"

If your desired date format isn't %F (i.e. YYYY-MM-DD), adapt to taste. (But keep in mind that it makes sense to have dates in computer-readable format; " 2 Aug 2021" is pleasant to read, but pesky to process. The one you are trying to use would be date +%d-%m-%Y, which is easy to recover, but hard e.g. to sort correctly. Similarly, it is trivial to convert a machine-readable date to a human-readable "pleasant" date for display purposes, but cumbersome or sometimes impossible to do the reverse.)

Upvotes: 5

Related Questions