How to Use Korn Shell (ksh) Variables in Linux

Introducing korn shell variables.

A variable refers to a temporary storage area in memory. Variables contain:

  • Information needed for customizing the shell
  • Information needed by other processes to function properly

The shell enables you to store values in variables. Korn shell programming uses two types of variables:

  • Variables that are exported to subprocesses
  • Variables that are not exported to subprocesses

The table below describes the Korn shell commands used to set, unset, and view variables.

When a shell variable follows the $ sign, the shell interprets that the value stored inside that variable is to be substituted at that point.

Referencing Values in Variables

You can use the echo command to display the value that is stored inside a shell variable. For example:

Displaying Variables

To list all shell variables with their current values, perform the set command. For example:

To make the value of a variable known to a sub-shell, export it using the export command. To view a list of all these variables and their current values, perform the export command:

Setting and Unsetting Shell Variables

A variable is set and a value is assigned with the following syntax:

There is no space on either side of the equal sign (=). For example:

To make the value of a variable known to a sub-shell, use the following command syntax:

For example:

You can delete the values stored in shell variables with the following command syntax:

For example, to unset the variable private, perform the following commands:

The output of the echo command is a blank line.

Displaying Default Variables

The table below describes variables that are assigned default values by the shell on login.

Customizing Korn Shell Variables

This section describes how to customize Korn shell variables.

The PS1 Prompt Variable

The shell prompt string is stored in the shell variable PS1, and you can customize it according to your preferences.

In this example, the prompt displays the login name of the user the system’s hostname and the current working directory. The username is read from the variable LOGNAME, and the hostname comes from the output of the ‘ uname -n ’ command. This prompt displays the correct information even when the user logs in on different hosts. The back quotation marks delimit an imbedded command string The following example shows how the value of another variable is used for prompt definition.

The PATH Variable

The PATH variable contains a list of directory path names, separated by colons. When you perform a command on the command line, the shell searches these directories from left to right to locate that command. The shell executes the first command that it finds. If the shell does not find the command in any of the listed directories, it displays the following error message:

The shell restricts its search to the directories specified in the PATH variable. Sometimes when the shell is unable to find a particular command, the command may reside in a directory that has not been specified in the PATH variable. When the shell is unable to find a particular command, the user can type the absolute path name of the directory in which the command resides. For example:

If the shell is able to successfully execute the command when you specify the absolute path name of the directory, check the PATH variable to ensure that the directory exists in the search path. If the directory exists in the search path, check that it has been named correctly. For example:

Extending the PATH Variable

To extend the PATH variable to include the home directory of the user, perform the following commands.

The PATH variable passes the value automatically to the sub-shells.

Using the Quoting Characters

Quoting is a process that instructs the shell to mask, or ignore, the special meaning of metacharacters. The quoting characters are single forward quotation marks (’’), double quotation marks (""), backslash (\), and parentheses ($( command )). Quotation marks around a string of metacharacters prevent the shell from interpreting the special meaning of the metacharacters. There are two types of quotation marks that mask the special meaning of metacharacters: single forward quotation marks (’’) and double quotation marks ("").

Single forward quotation marks instruct the shell to ignore all enclosed metacharacters. Double quotation marks instruct the shell to ignore all enclosed metacharacters, except for the following three characters:

1. The single backward quotation marks (‘) – Single backward quotation marks instruct the shell to execute and display the output for a UNIX system command. 2. The backslash (\) – A backslash (\) character in front of a metacharacter prevents the shell from interpreting the next character as a metacharacter. 3. The dollar sign ($) – You can also use parentheses () to perform command substitution. Parentheses ($( command )) instructs the shell to execute and display the output for the command enclosed within. The output of the nested command, command2, is substituted when the command1 command is executed. The syntax for this is:

To ignore the special meaning of the dollar sign metacharacter, perform the following command:

NOTE: The echo utility writes arguments to the standard output.

To interpret the special meaning of the dollar sign metacharacter, perform the following command:

To ignore the special meaning of the dollar sign metacharacter when you use double quotes, perform the following command:

To display the output for the date command, perform the following command:

To execute the pwd command using parentheses, perform the following command:

  • How To Change Engine Database Password for OLVM Engine
  • Oracle Linux Virtualization Manager(OLVM) Engine PostgreSQL Database Queries Cheat Sheet
  • How to Configure firewalld in CentOS/RHEL 8 using "Web Console" and "firewall-cmd"
  • Troubleshooting Booting Issues in CentOS/RHEL 7 and 8
  • How to Mount NFS Shares using Automounter in CentOS/RHEL
  • How to reset or recover root password in CentOS/RHEL 8
  • Understanding CentOS/RHEL 8 Boot Process
  • Beginners Guide to Stratis local storage management in CentOS/RHEL 8
  • How to Compress and Deduplicate Storage with VDO in CentOS/RHEL 8
  • How to Extend a Logical Volume in LVM - for XFS, ext4 and swap filesystem

Latest Posts

  • How to Create Index Partitions To Ranged Partitioned Table
  • How to Move Partition Online in Oracle 12c
  • How to add or modify Printer settings in CentOS/RHEL using GUI
  • What is machine-id in Linux

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

unix shell tips to assign boolean value to variable from a test

code to show the request in context (unix ksh currently):

is there a better, simplerway to assign r with true or false something like r=$( [ -z "foo" ]) (that seems to give an empty value) or r=[ -z "foo" ] that failed.

DavidPostill's user avatar

2 Answers 2

The [ ... ] construct (or the equivalent test ... ) returns a completion code of 0 for true or 1 for false, but it never generates any output, so $( [ ... ] ) always returns an empty string. The returned completion code is in $? , so r can be set to 0 or 1 by:

If you want the text values true and false in r (as opposed to 0 and 1), then your expression is basically correct, but the following is a bit simpler:

AFH's user avatar

  • basically that's what i do i my script. The echo is there because it assign a generic variable at en upper level in original script. i forget to use the $? as input, thanks for explanation –  NeronLeVelu Mar 20, 2018 at 14:06

Not the case here :

Gilles Quénot's user avatar

  • oops, sorry for the purpose i assign the value but it's the result of a test; I adapt the request. –  NeronLeVelu Mar 20, 2018 at 10:51

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged shell ksh ..

  • The Overflow Blog
  • Building GenAI features in practice with Intuit Mailchimp
  • A leading ML educator on what you need to know about LLMs
  • Featured on Meta
  • Changing how community leadership works on Stack Exchange: a proposal and...
  • Shifting the data dump schedule: A proposal

Hot Network Questions

  • If a fairy enters an antimagic field, do they die?
  • What punctuation do I use in "stage performers, their stage: the sky"?
  • Finding offset of a filesystem in LVM relative to beginning of a drive
  • problems in a good topology (subdivision)
  • Log scale of y-axis is still very small
  • Can 42 1x2x4 cuboids be packed into a 7x7x7 cube?
  • FizzBuzz on a List of Numbers
  • Why aren't congressmen/women arrested for interrupting State of the Union
  • Why does expelled former American congressperson, George Santos, still have access to the United States of America's Congressional House floor?
  • May sick Jews wait less for meat and dairy
  • What is the regurgitation process?
  • Is it correct to say that primary sources only exist in 'historical times', not in 'pre-history'?
  • Short story about a futuristic civilization that had no concept of there being a wider universe, and the ramifications of them discovering it?
  • What are the origins of these two uniforms?
  • Can the protium nucleus be in an excited state?
  • Number of surjective functions with given property
  • Is there an API that lets me hold flight bookings for free for 7 days with verifiable PNR?
  • Where exactly does the root directory exist in the linux filesystem?
  • How long does it take to charge a capacitor given constant power?
  • What does this sentence mean: "We got it closed into the pool gated area."
  • Replacing a compact fluorescent bulb in a bathroom exhaust fan with an LED bulb?
  • What is the difference between 楽天 and 楽観?
  • How do I increase the font size of the table?
  • Grounding ESD Table

assign variable ksh

Shell Programming and Scripting

Assigning multiple variables in ksh script.

Member Information Avatar

10 More Discussions You Might Find Interesting

1. shell programming and scripting, assigning multiple column's value from oracle query to multiple variables in unix, discussion started by: hkrishnan91, 2. shell programming and scripting, running a script with multiple variables like 25 variables., discussion started by: lakshman_gupta, 3. shell programming and scripting, how to store results of multiple sql queries in shell variables in ksh, discussion started by: gonchusirsa, 4. shell programming and scripting, ksh passing to awk multiple dyanamic variables awk -v, discussion started by: highnthemnts, 5. shell programming and scripting, awk issue expanding variables in ksh script, discussion started by: gazza-o, 6. shell programming and scripting, assigning values to reference variables for a dynamic menu driven script., discussion started by: kchinnam, 7. shell programming and scripting, awk splits file in to multiple - how to get filenames in variables withing ksh, discussion started by: spidermike, 8. shell programming and scripting, ksh help assigning specific values to variable in script, discussion started by: frustrated1, 9. shell programming and scripting, passing a variables value from the called script to calling script using ksh, discussion started by: rajarkumar, 10. shell programming and scripting, passing variables to awk from ksh script, discussion started by: rein, member badges and information modal.

The UNIX School

  • Shell Scripts
  • Different methods
  • awk & sed
  • Online Training

Wednesday, January 4, 2017

How to use arrays in ksh, no comments:, post a comment.

  • Oracle Visual Builder Page Model Reference
  • Understand the Page Model
  • JSON Action Chains
  • JSON Actions
  • Assign Variables Action

Metadata-Driven Variable Assignment

This action is used to assign values to a set of variables using metadata.

Metadata-driven variable assignment lets you use metadata to specify how assignment should be performed.

This form takes a map of target expression and assignment metadata pairs. For example, if the target expression is a structure, it has to resolve to a variable or to a variable's property. The target expression has to be prefixed with one of the following:

  • $application.variables
  • $page.variables
  • $chain.variables

This should be followed by a variable name or a path to a variable property, such as the following:

  • $application.variables.a
  • $page.variables.a.b
  • $variables.a.b.c

Note that $variables.a.b.c is a shortened form of $chain.variables.a.b.c .

The expression can be arbitrarily complex as long as it is a valid JavaScript expression and satisfies the above constraints.

The assignment metadata has the following format:

The "source" expression can be an arbitrary expression that evaluates to a primitive value, an object or an array.

The "reset" option can be one of the following:

"toDefault" - reset the target to its default value before assignment. This is the default.

"empty" - clear the target before assignment. If the target has an object type, the target will be reset to an empty object of that type. If the target is an array, the target will be reset to an empty array.

"none" - overwrite the existing target value

The "auto" option controls whether to auto-assign all properties from the source to the corresponding properties of the target. It can be set to one of the following:

"always" - auto-assignment will always be performed first before any mapping is applied.

"ifNoMapping": auto-assignment will only be performed if no mapping is provided. This is the default.

The "mapping" is a piece of metadata used to provide fine-grained control over what gets assigned from the source to the target. When no "mapping" is used to control the assignment, there are two possible schemes for assignment depending on the target type, auto and direct .

If the target has a concrete type, the assign action will auto-assign the source to the target. If the target type is an object type, auto-assignment will recursively assign each property in the source object to the corresponding property in the target object based on the target type. If the target is an array, the source will be treated as an array if it is not one already. For each item of the source array, an empty item will be created using the target's array item type and appended to the target array. The source item is then auto-assigned to the target item. 

If the target property is an object and the source property is a primitive or vice versa, no assignment will be made. For primitive types, the source value will be coerced into the target type before assignment. For boolean type, the coercion will be based on whether the source value is truthy except for "false" (case-insensitive) and "0" which will be coerced to false.

If the target has a wildcard type, e.g., any, any[], object or object[], direct assignment will be performed. The behavior may differ depending on the wildcard type:

any - the source value is directly assigned to the target

any[] - the source value is turned into an array if not one already and then directly assigned to the target

object - same as any except the source value has to be an object. Otherwise, no assignment is performed.

object[] - same as any[] except the items in the source array have to be objects. Otherwise, no assignment is performed.

Example : Metadata-driven assignment takes a map of target expression and assignment metadata pairs.

IMAGES

  1. How to give variable to a KSH script with a CGI?

    assign variable ksh

  2. Unix & Linux: ksh variable declaration and loop (2 Solutions!!)

    assign variable ksh

  3. Unix & Linux: Creating a variable with sed in ksh (2 Solutions!!)

    assign variable ksh

  4. KSH For Loop Examples

    assign variable ksh

  5. Unix & Linux: How to use Variable for grep inside Ksh script?

    assign variable ksh

  6. ksh

    assign variable ksh

VIDEO

  1. V10 Data Factory Lookup and Set Variables Activities

  2. Beginners guide to Mainstage for Marching Arts

  3. Freidor para tostadas

  4. Index Number Introduction and Types of Index Number in Urdu

  5. Best code editor for Python

  6. SE1-05 Creating and Using Variables

COMMENTS

  1. shell

    How can you get a variable's value given its name in korn shell? 4. KornShell - Test with variable that may be not set. 0. unix ksh assign two values to a variable. 0. Assign value to a variable in a for loop via KornShell. 12. Scope of variables in KSH. 1. Building Dynamic Variable Names in KornShell. 1.

  2. How to Use Korn Shell (ksh) Variables in Linux

    The table below describes the Korn shell commands used to set, unset, and view variables. Action. Command. To set a variable. VAR=value export VAR=value. To unset a variable. unset VAR. To display all variables. set, env, or export.

  3. Variable assignment in a ksh script

    As @Julie Pelletier indicated, this is funny syntax to make a indirect variable, or a nameref.ksh has some specialized syntax to make this work, however. This is a feature of ksh, and might not work in other shells.. The more idiomatic way to write the same in ksh would look like this: # Set up the nameref: nameref temprule=APPLC_NM # Assign value to AAPLC_NM APPLC_NM=abc # The above two ...

  4. Variables and Parameters in the Korn Shell

    Variables and parameters are used by the Korn shell to store values. Like other high-level programming languages, the Korn shell supports data types and arrays. This is a major difference with the Bourne, C shell, and other scripting languages, which have no concept of data types. The Korn shell supports four data types: string, integer, float ...

  5. Korn Shell Variables

    Rules For Naming Korn Shell Variables. Korn shell variable names can begin with an alphabetic (a-Z) or underscore character. Other variable names that contain only digits (0-9) or special characters (!, @, #, %, *, ?, $) are reserved for special parameters set directly by the Korn shell.

  6. Quoting

    Quoting. Quotes are used when assigning values containing whitespace or special characters, to delimit parameters and variables, and to assign command output. There are three types of quotes: single quotes, double quotes, and back quotes. Single and double quotes are similar, except for the way they handle some special characters.

  7. Linux / Unix: Bash Shell Assign Printf Result To Variable

    How to assign a grep command value to a variable in… Shell Scripting: If Variable Is Not Defined, Set… KVM libvirt assign static guest IP addresses using…

  8. ksh

    1. code to show the request in context (unix ksh currently): r=$ ( [ -z "foo" ] && echo true || echo false ) is there a better, simplerway to assign r with true or false something like r=$ ( [ -z "foo" ]) (that seems to give an empty value) or r= [ -z "foo" ] that failed. shell. ksh.

  9. ksh help assigning specific values to variable in script

    ksh help assigning specific values to variable in script. Hi - Help needed. I have an input file that looks something like this, but with a lot more entries: Code: A Customer1 B 4500 C 8000 A Customer2 B 6422 C 8922. I need to be able to print details for each customer on one line per customer. ie. if I could print these to a file and then cat ...

  10. Assigning multiple variables in ksh script

    Hi All, I need to read values of 10 columns from oracle query and assign the same to 10 unix variables. The query will return only one record(row). I tried to append all these columns using a delimiter(;) in the select query and assign the same to a single variable(V) in unix.

  11. How to use arrays in ksh?

    One important difference here is shells support only one-dimensional arrays. 1. Creating an array: Creating an array is pretty simple. $ typeset -a arr. $ arr[0]=25. $ arr[1]=18. $ arr[2]="hello". Using the typeset command, we let the shell know that we are intending to use the variable arr to store a list of elements.

  12. Assigning values to variables in ksh

    Assigning values to variables in ksh. Ask Question Asked 9 years, 7 months ago. Modified 9 years, 7 months ago. Viewed 238 times 0 I am trying to find out a way to assign values to variables from a file. My file has . PID=1 VALUE=1000 CMD=/usr/bin/ls -l i want to assign right part of "=" symbol as value to the left side name, This leftside name ...

  13. Metadata-Driven Variable Assignment

    This action is used to assign values to a set of variables using metadata. Metadata-driven variable assignment lets you use metadata to specify how assignment should be performed. This form takes a map of target expression and assignment metadata pairs. For example, if the target expression is a structure, it has to resolve to a variable or to ...

  14. ksh

    In ksh/zsh/bash/yash, you may want to use arrays instead (or associative arrays in ksh93, zsh or recent versions of bash). Note that ksh / bash array indices start at 0 and arrays are sparse (more like associative arrays with keys limited to positive integers) while in all other shells (including zsh and yash on the Bourne-like front), indices ...

  15. Checking a variable is set and value in ksh

    The thing to be careful of is the right hand side in the event that it is a variable or a string that could be evaluated for things other than just a simple string comparison. Consider these:

  16. viewing variable values in a KSH script

    In ksh, proper use of variable substitutions is ${variable_name}. And yes, you can echo this to your terminal or use it in a test command, i.e. if [ ${variable_name} - eq ${mynumber} ] etc. If you skip using the curly brackets, it still works most of the time but, you will be more prone to making mistakes.