Skip to content

Commit 00940d2

Browse files
committed
scripting continued
1 parent 152d17d commit 00940d2

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

unix/scripting_marathon.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,3 +90,42 @@ or a command. In bash, the correct way to store a command in a variable is withi
9090
`variable=$(command –options arguments)`
9191

9292
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.
130+
131+
### if / then / else

0 commit comments

Comments
 (0)