كيفية التعامل مع المتغيرات في Bash

تعتبر المتغيرات ضرورية إذا كنت ترغب في كتابة نصوص وفهم ما سيفعله هذا الرمز الذي توشك على قصه ولصقه من الويب على كمبيوتر Linux الخاص بك. سنبدأ بك!

المتغيرات 101

المتغيرات هي رموز مسماة تمثل إما سلسلة أو قيمة رقمية. عند استخدامها في الأوامر والتعبيرات ، يتم التعامل معها كما لو كنت قد كتبت القيمة التي تحتوي عليها بدلاً من اسم المتغير.

لإنشاء متغير ، ما عليك سوى توفير اسم وقيمة له. يجب أن تكون أسماء المتغيرات الخاصة بك وصفية وتذكرك بالقيمة التي تحملها. لا يمكن أن يبدأ اسم المتغير برقم ولا يمكن أن يحتوي على مسافات. ومع ذلك ، يمكن أن تبدأ بشرطة سفلية. بصرف النظر عن ذلك ، يمكنك استخدام أي مزيج من الأحرف الأبجدية الرقمية الكبيرة والصغيرة.

أمثلة

هنا ، سننشئ خمسة متغيرات. التنسيق هو كتابة الاسم وعلامة التساوي =والقيمة. لاحظ أنه لا توجد مسافة قبل علامة التساوي أو بعدها. غالبًا ما يشار إلى إعطاء قيمة متغير على أنه تعيين قيمة للمتغير.

سننشئ أربعة متغيرات سلسلة ومتغير رقمي واحد ، this_year:

أنا = ديف
my_boost = لينكس
له = بوباي
his_boost = السبانخ
this_year = 2019

لمعرفة القيمة المحفوظة في متغير ، استخدم echoالأمر. يجب أن تسبق اسم المتغير بعلامة الدولار $عندما تشير إلى القيمة التي يحتوي عليها ، كما هو موضح أدناه:

صدى $ my_name
صدى $ my_boost
صدى $ this_year

دعنا نستخدم جميع المتغيرات مرة واحدة:

صدى "$ my_boost هو $ me حيث أن $ his_boost هو $ him (c) $ this_year"

قيم المتغيرات تحل محل أسمائها. يمكنك أيضًا تغيير قيم المتغيرات. لتعيين قيمة جديدة للمتغير ، ما  my_boostعليك سوى تكرار ما فعلته عندما عيّنت قيمته الأولى ، مثل:

my_boost = تيكيلا

إذا أعدت تشغيل الأمر السابق ، فستحصل الآن على نتيجة مختلفة:

صدى "$ my_boost هو $ me حيث أن $ his_boost هو $ him (c) $ this_year"

لذلك ، يمكنك استخدام نفس الأمر الذي يشير إلى نفس المتغيرات والحصول على نتائج مختلفة إذا قمت بتغيير القيم الموجودة في المتغيرات.

سنتحدث عن اقتباس المتغيرات لاحقًا. في الوقت الحالي ، إليك بعض الأشياء التي يجب تذكرها:

  • ' يتم التعامل مع المتغير في علامات الاقتباس الفردية كسلسلة حرفية ، وليس كمتغير.
  • "  يتم التعامل مع المتغيرات الموجودة بين علامات الاقتباس كمتغيرات.
  • للحصول على القيمة المحتفظ بها في متغير ، يجب عليك تقديم علامة الدولار $.
  • المتغير بدون علامة الدولار $ يوفر فقط اسم المتغير.

يمكنك أيضًا إنشاء متغير يأخذ قيمته من متغير موجود أو عدد من المتغيرات. ويعرف الأمر التالي متغير جديد يسمى drink_of_the_Year,ويسند القيم المشتركة لل my_boostو this_yearالمتغيرات:

drink_of-the_Year = "$ my_boost $ this_year"
صدى drink_of_the- السنة

كيفية استخدام المتغيرات في النصوص

البرامج النصية ستتعطل تمامًا بدون متغيرات. توفر المتغيرات المرونة التي تجعل البرنامج النصي حلاً عامًا وليس حلاً محددًا. لتوضيح الاختلاف ، إليك نص برمجي يحسب الملفات الموجودة في /devالدليل.

اكتب هذا في ملف نصي ، ثم احفظه باسم fcnt.sh(لـ "عدد الملفات"):

#! / bin / bash folder_to_count = / dev file_count = $ (ls $ folder_to_count | wc -l) صدى $ file_count الملفات في $ folder_to_count

قبل أن تتمكن من تشغيل البرنامج النصي ، يجب أن تجعله قابلاً للتنفيذ ، كما هو موضح أدناه:

chmod + x fcnt.sh

اكتب ما يلي لتشغيل البرنامج النصي:

./fcnt.sh

هذا يطبع عدد الملفات في /devالدليل. وإليك كيف يعمل:

  • folder_to_countيتم تعريف متغير يسمى ، ويتم تعيينه ليحتوي على السلسلة "/ dev."
  • file_countيتم تعريف متغير آخر يسمى  . يأخذ هذا المتغير قيمته من استبدال الأمر. هذه هي جملة الأمر بين الأقواس $( ). لاحظ أن هناك علامة الدولار $قبل القوس الأول. $( )يقيم هذا البناء الأوامر داخل الأقواس ، ثم يُرجع قيمتها النهائية. في هذا المثال ، يتم تخصيص هذه القيمة file_countللمتغير. بقدر ما يتعلق الأمر file_countبالمتغير ، يتم تمرير قيمة للاحتفاظ به ؛ لا يتعلق الأمر بكيفية الحصول على القيمة.
  • يقوم الأمر الذي تم تقييمه في استبدال الأوامر lsبإدراج ملف في الدليل في folder_to_countالمتغير ، والذي تم تعيينه على "/ dev." لذلك ، ينفذ البرنامج النصي الأمر "ls / dev."
  • The output from this command is piped into the wc command. The -l (line count) option causes wc to count the number of lines in the output from the ls command. As each file is listed on a separate line, this is the count of files and subdirectories in the “/dev” directory. This value is assigned to the file_count variable.
  • The final line uses echo to output the result.

But this only works for the “/dev” directory. How can we make the script work with any directory? All it takes is one small change.

How to Use Command Line Parameters in Scripts

Many commands, such as ls and wc, take command line parameters. These provide information to the command, so it knows what you want it to do. If you want ls to work on your home directory and also to show hidden files, you can use the following command, where the tilde ~ and the -a (all) option are command line parameters:

ls ~ -a

Our scripts can accept command line parameters. They’re referenced as $1 for the first parameter, $2 as the second, and so on, up to $9 for the ninth parameter. (Actually, there’s a $0, as well, but that’s reserved to always hold the script.)

You can reference command line parameters in a script just as you would regular variables. Let’s modify our script, as shown below, and save it with the new name fcnt2.sh:

#!/bin/bash  folder_to_count=$1  file_count=$(ls $folder_to_count | wc -l)  echo $file_count files in $folder_to_count

This time, the folder_to_count variable is assigned the value of the first command line parameter, $1.

The rest of the script works exactly as it did before. Rather than a specific solution, your script is now a general one. You can use it on any directory because it’s not hardcoded to work only with “/dev.”

Here’s how you make the script executable:

chmod +x fcnt2.sh

Now, try it with a few directories. You can do “/dev” first to make sure you get the same result as before. Type the following:

./fnct2.sh /dev
./fnct2.sh /etc
./fnct2.sh /bin

You get the same result (207 files) as before for the “/dev” directory. This is encouraging, and you get directory-specific results for each of the other command line parameters.

To shorten the script, you could dispense with the variable, folder_to_count, altogether, and just reference $1 throughout, as follows:

#!/bin/bash   file_count=$(ls $1  wc -l)   echo $file_count files in $1

Working with Special Variables

We mentioned $0, which is always set to the filename of the script. This allows you to use the script to do things like print its name out correctly, even if it’s renamed. This is useful in logging situations, in which you want to know the name of the process that added an entry.

The following are the other special preset variables:

  • $#: How many command line parameters were passed to the script.
  • $@: All the command line parameters passed to the script.
  • $?: The exit status of the last process to run.
  • $$: The Process ID (PID) of the current script.
  • $USER: The username of the user executing the script.
  • $HOSTNAME: The hostname of the computer running the script.
  • $SECONDS: The number of seconds the script has been running for.
  • $RANDOM: Returns a random number.
  • $LINENO: Returns the current line number of the script.

You want to see all of them in one script, don’t you? You can! Save the following as a text file called, special.sh:

#!/bin/bash  echo "There were $# command line parameters" echo "They are: $@" echo "Parameter 1 is: $1" echo "The script is called: $0" # any old process so that we can report on the exit status pwd echo "pwd returned $?" echo "This script has Process ID $$" echo "The script was started by $USER" echo "It is running on $HOSTNAME" sleep 3 echo "It has been running for $SECONDS seconds" echo "Random number: $RANDOM" echo "This is line number $LINENO of the script"

Type the following to make it executable:

chmod +x special.sh

Now, you can run it with a bunch of different command line parameters, as shown below.

Environment Variables

Bash uses environment variables to define and record the properties of the environment it creates when it launches. These hold information Bash can readily access, such as your username, locale, the number of commands your history file can hold, your default editor, and lots more.

To see the active environment variables in your Bash session, use this command:

env | less

If you scroll through the list, you might find some that would be useful to reference in your scripts.

How to Export Variables

When a script runs, it’s in its own process, and the variables it uses cannot be seen outside of that process. If you want to share a variable with another script that your script launches, you have to export that variable. We’ll show you how to this with two scripts.

First, save the following with the filename script_one.sh:

#!/bin/bash  first_var=alpha second_var=bravo  # check their values echo "$0: first_var=$first_var, second_var=$second_var"  export first_var export second_var  ./script_two.sh  # check their values again echo "$0: first_var=$first_var, second_var=$second_var"

This creates two variables, first_var and second_var, and it assigns some values. It prints these to the terminal window, exports the variables, and calls script_two.sh. When script_two.sh terminates, and process flow returns to this script, it again prints the variables to the terminal window. Then, you can see if they changed.

The second script we’ll use is script_two.sh. This is the script that script_one.shcalls. Type the following:

#!/bin/bash  # check their values echo "$0: first_var=$first_var, second_var=$second_var"  # set new values first_var=charlie second_var=delta  # check their values again echo "$0: first_var=$first_var, second_var=$second_var"

This second script prints the values of the two variables, assigns new values to them, and then prints them again.

To run these scripts, you have to type the following to make them executable:

chmod +x script_one.sh chmod +x script_two.sh

And now, type the following to launch script_one.sh:

./script_one.sh

This is what the output tells us:

  • script_one.sh prints the values of the variables, which are alpha and bravo.
  • script_two.sh prints the values of the variables (alpha and bravo) as it received them.
  • script_two.sh changes them to charlie and delta.
  • script_one.sh prints the values of the variables, which are still alpha and bravo.

What happens in the second script, stays in the second script. It’s like copies of the variables are sent to the second script, but they’re discarded when that script exits. The original variables in the first script aren’t altered by anything that happens to the copies of them in the second.

How to Quote Variables

You might have noticed that when scripts reference variables, they’re in quotation marks ". This allows variables to be referenced correctly, so their values are used when the line is executed in the script.

If the value you assign to a variable includes spaces, they must be in quotation marks when you assign them to the variable. This is because, by default, Bash uses a space as a delimiter.

Here’s an example:

site_name=How-To Geek

Bash sees the space before “Geek” as an indication that a new command is starting. It reports that there is no such command, and abandons the line. echo shows us that the site_name variable holds nothing—not even the “How-To” text.

Try that again with quotation marks around the value, as shown below:

site_name="How-To Geek"

This time, it’s recognized as a single value and assigned correctly to the site_name variable.

echo Is Your Friend

It can take some time to get used to command substitution, quoting variables, and remembering when to include the dollar sign.

Before you hit Enter and execute a line of Bash commands, try it with echo in front of it. This way, you can make sure what’s going to happen is what you want. You can also catch any mistakes you might have made in the syntax.