Sathish Kumar
Sathish Kumar

Reputation: 2556

How to export multiple variables with same value in ksh?

I want to set the following variables to the same value in one single line

Example:  export A=B=C=20

There is a syntax available in 'bash' but how can I accomplish the above in ksh ?

Upvotes: 33

Views: 71981

Answers (6)

sudhanthira mohan
sudhanthira mohan

Reputation: 1

In my case I had to capture the return value and the exit code of the snowsql command in Bash. This is how it worked for me:

export ret_value=$(snowsql command) rc=$?

Upvotes: -1

Toby Speight
Toby Speight

Reputation: 30876

You can use brace-expansion (at least in the MirBSD version of ksh) to assign and export several variables:

export {A,B,C}=20

Exactly the same command also works in Bash.

Upvotes: 1

pjboro
pjboro

Reputation: 148

Here is a portable, although a bit wordy solution. The advantage over arithmetic notation is that it works also for strings:

$ for v in A B C D; do export $v=value; done
$ env | grep -E ^.=
_=*82496*/usr/bin/env
A=value
B=value
C=value
D=value
$ ksh --version
  version         sh (AT&T Research) 2020.0.0

Upvotes: 4

Henk Langeveld
Henk Langeveld

Reputation: 8456

Ksh93 (or bash) doesn't have such expressions, so it's better to make it explicit. But you can bundle multiple variables (with their initial values) in a single export phrase:

export A=1 B=2 C=3

Testing:

$ (export A=1 B=2 C=3 && ksh -c 'echo A=$A B=$B C=$C D=$D')
A=1 B=2 C=3 D=

Awkward alternatives

There is no C-like shortcut, unless you want this ugly thing:

A=${B:=${C:=1}}; echo $A $B $C
1 1 1

... which does not work with export, nor does it work when B or C are empty or non-existent.

Arithmetic notation

Ksh93 arithmetic notation does actually support C-style chained assignments, but for obvious reasons, this only works with numbers, and you'll then have to do the export separately:

$ ((a=b=c=d=1234))
$ echo $a $b $c $d
1234 1234 1234 1234
$ export a b d
$ ksh -c 'echo a=$a b=$b c=$c d=$d'     # Single quotes prevent immediate substitution
a=1234 b=1234 c= d=d1234                # so new ksh instance has no value for $c

Note how we do not export c, and its value in the child shell is indeed empty.

Upvotes: 57

papaiatis
papaiatis

Reputation: 4291

Here is my example solution for this:

$> export HTTP_PROXY=http://my.company.proxy:8080 && export http_proxy=$HTTP_PROXY https_proxy=$HTTP_PROXY HTTPS_PROXY=$HTTP_PROXY

$> printenv | grep -i proxy
http_proxy=http://my.company.proxy:8080
HTTPS_PROXY=http://my.company.proxy:8080
https_proxy=http://my.company.proxy:8080
HTTP_PROXY=http://my.company.proxy:8080

Explanation

At first I set the HTTP_PROXY variable with export and execute that command and only after that (&& notes that) set the remaining variables to the same value as of HTTP_PROXY.

Upvotes: 2

Raj
Raj

Reputation: 35

export a=60 && export b=60 && export c=60

May not be the best option if you have many variables

Upvotes: 1

Related Questions