Character Expansion in Shell Programming

${strings}other_stuff

After a quick search, saw someone saying it was character expansion in the shell. The original text is called ${filename} Construct. Because, what is discussed here is that when operating on files, some of the file names are the same and some are different. At this time, how to deal with it?

After logging in to the system with ssh, write the simplest program called pro

you pro

//Write these two lines in pro

$filename=t

mv $filename $filename1

For example, Apache log files, if left alone, can become very large, reaching tens of gigabytes. Of course, it depends on the number of visits to the website. These log files can be split into smaller pieces. Save as one each week. Only log files from the last 4 weeks are kept. At 12:00 on Sunday night, the log needs to be renamed. The latter 1 becomes the date of the day, such as suffix=`date -d today +%Y-%m-%d`, similar to the above example.

save, exit. Make this program executable.

chmod +x pro

Create a file named t in the current directory

touch t

then run this pro

./pro //I am in the current path

I want to see that the t under the current path becomes t1. But after running it, an error occurred.

mv: ‘./t’ and ‘./t’ are the same file

Just asking you to rename the file, the content must be the same. Why so much nonsense? No, what it's doing is renaming t to t, not t1 as I want. Not only the content is the same, but the file name is also the same. Follow the steps below, modify the pro, and you're good to go.

mv $filename ${filename}1

In practical applications, this may be the case:

filename=access_log

suffix=`date -d today +%Y-%m-%d`

mv $filename ${filename}$suffix

Copy the original text here.

The ${variable} Construct
Suppose that you have the name of a file stored in the variable filename. If you wanted to
rename that file so that the new name was the same as the old, except with an X added to the
end, your first impulse would be to type

mv $filename $filenameX

When the shell scans this command line, however, it substitutes the value of the variable
filename and also the value of the variable filenameX. The shell thinks filenameX is the full
name of the variable because it’s composed entirely of valid characters.
To avoid this problem, delimit the variable by enclosing the entire name (but not the leading
dollar sign) in curly braces, as in

${filename}X

This removes any ambiguity, and the mv command then works as desired:

mv $filename ${filename}X

Remember that the braces are necessary only if the last character of the variable name is
followed by an alphanumeric character or an underscore.


There are also quite a few functions applicable to variables within this curly brace notation,
including extracting subsets, assigning values if the variable is currently unassigned, and more.
Stay tuned for those!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325469848&siteId=291194637