Home > Articles > Operating Systems, Server > Linux/UNIX/Open Source

This chapter is from the book

Variable Expansion

Variable expansion is the term used for the ability to access and manipulate values of variables and parameters. Basic expansion is done by preceding the variable or parameter name with the $ character. This provides access to the value.

$ UULIB=/usr/lib/uucp 
   $ print $UULIB 
   /usr/lib/uucp 

Other types of expansion can be used to return portions or the length of variables, use default or alternate values, check for mandatory setting, and more.

For the sake of convenience, the term variable will refer to both variables and parameters in the following sections that discuss variable expansion.

$ variable, ${variable}

This is expanded to the value of variable. The braces are used to protect or delimit the variable name from any characters that follow. The next example illustrates why braces are used in variable expansion. The variable CA is set to ca:

$ CA=ca 

What if we wanted to reset CA to california? It could be reset to the entire value, but to make a point, let's try using the current value like this:

$ CA=$CAlifornia 
   $ print $CA 
   
   $ 

Nothing is printed, because without the braces around the variable CA, the Korn shell looks for a variable named $CAlifornia. None is found, so nothing is substituted. With the braces around variable CA, we get the correct value:

$ CA=${CA}lifornia 
   $ print $CA 
   california 

Braces are also needed when attempting to expand positional parameters greater than 9. This ensures that both digits are interpreted as the positional parameter name.

${#variable}

This is expanded to the length of variable. In this example, X is set to a three-character string, so a length of 3 is returned:

$ X=abc 
   $ print ${#X} 
   3 

Whitespace in variable values is also counted as characters. Here the whitespace from the output of the date command is also counted:

$ TODAY=$(date) 
   $ print ${#TODAY} 
   28 

${variable:—word}, ${variableword}

This is expanded to the value of variable if it is set and not null, otherwise word is expanded. This is used to provide a default value if a variable is not set. In the following example, the variable X is set to abc. When expanded using this format, the default value abc is used:

$ X=abc 
   $ print ${X:—cde} 
   abc 

After X is unset, the alternate value cde is used:

$ unset X 
   $ print ${X:—cde} 
   cde 

Notice that the value of X remains unchanged:

$ print $X 
   
   $ 

Let's say we needed a command to get the user name. The problem is that some people have it set to USER, while others have it set to LOGNAME. We could use an if command to check one value first, then the other. This would be quite a few lines of code. Or we could use this form of variable expansion to have both values checked with one command. Here, if USER is set, then its value is displayed, otherwise the value of LOGNAME is displayed.

$ print USER=$USER, LOGNAME=$LOGNAME 
   USER=anatole, LOGNAME=AO 
   $ print ${USER:—${LOGNAME}} 
   anatole 

Now we unset USER to check and make sure that LOGNAME is used:

$ unset USER 
   $ print ${USER:—${LOGNAME}} 
   AO 

But what if both USER and LOGNAME are not set? Another variable could be checked like this:

$ print ${USER:—${LOGNAME:—${OTHERVAR}}} 

But to demonstrate other ways that the alternate value can be expanded, let's just use some text.

$ unset USER LOGNAME 
   $ print ${USER:-${LOGNAME:-USER and LOGNAME \ 
   not set!}} 
   USER and LOGNAME not set! 

In this version, the output of the whoami command is used:

$ print ${USER—${LOGNAME:—$(whoami)}} 
   anatole 

For compatibility with the Bourne shell, it could also be given as:

$ echo ${USER:—${LOGNAME:—`whoami`}} 
   anatole 

Remember that the alternate value is only used and not assigned to anything. The next section shows how you can assign an alternate value if a default value is not set. The other format, ${variable– word}, causes the variable value to be used, even if it is set to null:

$ typeset X= 
   $ print ${X-cde} 
   
   $ 

${variable:= word}, ${variable=word}

This is expanded to the value of variable if set and not null, otherwise it is set to word, then expanded. In contrast to the variable expansion format from the previous section, this format is used to assign a default value if one is not already set. In the next example, the variable LBIN is set to /usr/lbin. When expanded using this format, the default value /usr/lbin is used:

$ LBIN=/usr/lbin 
   $ print ${LBIN:=/usr/local/bin} 
   /usr/lbin 

After LBIN is unset, this form of variable expansion causes LBIN to be assigned the alternate value, /usr/local/bin:

$ unset LBIN 
   $ print ${LBIN:=/usr/local/bin} 
   /usr/local/bin 

Notice that LBIN is now set to /usr/local/bin.

$ print $LBIN 
   /usr/local/bin 

Command substitution can also be used in place of word. This command sets the SYS variable using only one command:

$ unset SYS 
   $ print ${SYS:=$(hostname)} 
   aspd 

The other format, ${variable=word}, causes the variable value to be used, even if it is set to null. Here LBIN is not assigned an alternate value. If := was used instead of =, then LBIN would be set to /usr/local/bin:

$ LBIN= 
   $ print ${LBIN=/usr/local/bin} 
   
   $ 

${variable:?word}, ${variable:?}, ${variable?word}, ${variable?}

This is expanded to the value of variable if it is set and not null, otherwise word is printed and the Korn shell exits. If word is omitted, 'parameter null or not set' is printed. This feature is often used in Korn shell scripts to check if mandatory variables are set. In this example, variable XBIN is first unset. When expanded, the default error is printed:

$ unset XBIN 
   $ : ${XBIN:?} 
   /bin/ksh: XBIN: parameter null or not set 

The ? as the word argument causes the default error message to be used. You could also provide your own error message:

$ print ${XBIN:?Oh my God, XBIN is not set!} 
   /bin/ksh: XBIN: Oh my God, XBIN is not set! 

The other formats, ${variable?word} and ${variable?}, cause the variable value to be used, even if it is set to null.

${variable:+word}, ${variable+word}

This is expanded to the value of word if variable is set and not null, otherwise nothing is substituted. This is basically the opposite of the ${variable:word} format. Instead of using word if variable is not set, word is used if variable is set. In the first example Y is set to abc. When expanded, the alternate value def is displayed because Y is set:

$ Y=abc 
   $ print ${Y:+def} 
   def 

Here, Y is unset. Now when expanded, nothing is displayed:

$ unset Y 
   $ print ${Y:+def} 
   
   $ 

Like the ${variable:word} format, the alternate value is only used and not assigned to the variable. Y is still set to null:

$ print $Y 
   
   $ 

The other format, ${variable+word}, causes the variable value to be used, even if it is set to null:

$ Y= 
   $ print ${Y+def} 
   def 

${variable#pattern}, ${variable##pattern}

This is expanded to the value of variable with the smallest (#) or largest (##) part of the left matched by pattern deleted. What these expansion formats allow you to do is manipulate substrings. To demonstrate the basic functionality, X is set to a string that contains a recurring pattern: abcabcabc.

$ X=abcabcabc 

When expanded to return the substring that deletes the smallest left pattern abc, we get abcabc:

$ print ${X#abc*} 
   abcabc 

while the substring that deletes the largest left pattern abc is abcabcabc, or the entire string:

$ print ${X##abc*} 
   
   $ 

Table 3.5. Variable Expansion Formats

${#variable}

length of variable

${variable:–word}

value of variable if set and not null, else print word

${variable:= word}

value of variable if set and not null, else variable is set to word, then expanded

${variable:+word}

value of word if variable is set and not null, else nothing is substituted

${variable:?}

value of variable if set and not null, else print 'variable: parameter null or not set'

${variable:?word}

value of variable if set and not null, else print value of word and exit

${variable #pattern}

value of variable without the smallest beginning portion that matches pattern

${variable ##pattern}

value of variable without the largest beginning portion that matches pattern

${variable%pattern}

value of variable without the smallest ending portion that matches pattern

${variable%%pattern}

value of variable without the largest ending portion that matches pattern

${variable//pattern1/pattern2}

replace all occurrences of pattern1 with pattern2 in variable

We could use this concept to implement the Korn shell version of the Unix basename command. The pattern in this command causes the last directory to be returned if variable X is set to a full pathname:

$ X=/usr/spool/cron 
   $ print ${X##*/} 
   cron 

${variable%pattern}, ${variable%%pattern}

This is expanded to the value of variable with the smallest (%) or largest (%%) part of the right matched by pattern deleted. This is the same as the parameter expansion format from the previous section, except that patterns are matched from the right instead of left side. It could also be used to display file names without their .suffixes:

$ X=file.Z 
   $ print ${X%.*} 
   file 

Here, any trailing digits are stripped:

$ X=chap1 
   $ print ${X%%[0—9]*} 
   chap 
   $ X=chap999 
   $ print ${X%%[0—9]*} 
   chap 

The pattern in this command causes it to act like the Unix dirname command. Everything except the last directory is returned if variable X is set to a full pathname.

$ X=/usr/spool/cron 
   $ print ${X%/*} 
   /usr/spool 

${variable//pattern1/pattern2}, ${variable/pattern1/pattern2}, ${variable#pattern1/pattern2}, ${variable/%pattern1/pattern2}

The Korn shell supports four search and replace operations on variables. This example changes all occurrences of abc in X to xyz:

$ X=abcabcabc 
   $ print ${X//abc/xyz} 
   xyzxyzxyz 

while this one only changes the first occurrence of abc in X to xyz:

$ X=abcabcabc 
   $ print ${X/abc/xyz} 
   xyzabcabc 

See Table 3.6 for detailed explanation of the other formats.

${variable:start}, ${variable:start:length}

This format returns a substring. The first returns variable from position start to end, while the second returns length characters from variable from character position start to end. For example, this returns the first 3 characters of X:

$ X=abcdefghij 
   $ print {$X:0:3} 
   abc 

while this example returns the value of X starting at character position 5:

$ X=abcdefghij 
   $ print {$X:5} 
   fghij 

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020