You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: unix/scripting_marathon.md
+39Lines changed: 39 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -90,3 +90,42 @@ or a command. In bash, the correct way to store a command in a variable is withi
90
90
`variable=$(command –options arguments)`
91
91
92
92
Store the date and time in a variable. Test the date command first in your terminal, then when you got the right format, store it in a variable in your script.
93
+
94
+
It is generally bad practice to put spaces in file names in unix, so we'll want the following date format:
95
+
96
+
`date +%m_%d_%y-%H.%M.%S`
97
+
98
+
and for putting it into a variable:
99
+
100
+
date_formatted=$(date +%m_%d_%y-%H.%M.%S)
101
+
102
+
Your script now can print thedate without too much more coding:
103
+
104
+
```
105
+
#!/usr/bin/env bash
106
+
107
+
# this script will copy a file, appending the data and time to
108
+
# the end of the file name
109
+
110
+
date_formatted=$(date +%m_%d_%y-%H.%M.%S)
111
+
echo "This is the date and time:" $date_formatted
112
+
113
+
```
114
+
115
+
Now we need to add the copying part:
116
+
117
+
`cp –iv $1 $2.$date_formatted`
118
+
119
+
This will invoke the copy command, with two options: -i for asking for permission before overwriting a file, and -v for verbose.
120
+
121
+
You can also notice two variables: $1 and $2. When scripting in bash, a dollar sign ($) followed by a number will denote an argument of the script. For example in the following command:
122
+
123
+
`cp –iv a_file a_file_copy` the first argument ($1) is `a_file` and the second argument ($2) is `a_file_copy`
124
+
125
+
What our script will do is a simple copy of a file, but with adding the date to the end of the file name. Save it and try it out!
126
+
127
+
## Conditionals
128
+
129
+
Conditionals let you decide whether to perform an action or not, this decision is taken by evaluating an expression.
0 commit comments