How to check for space in a variable in bash?
I am taking baby steps at learning bash and I am developing a piece of code which takes an input and checks if it contains any spaces. The idea is that the variable should NOT contain any spaces and the code should consequently echo a suitable message.
bash
add a comment |
I am taking baby steps at learning bash and I am developing a piece of code which takes an input and checks if it contains any spaces. The idea is that the variable should NOT contain any spaces and the code should consequently echo a suitable message.
bash
add a comment |
I am taking baby steps at learning bash and I am developing a piece of code which takes an input and checks if it contains any spaces. The idea is that the variable should NOT contain any spaces and the code should consequently echo a suitable message.
bash
I am taking baby steps at learning bash and I am developing a piece of code which takes an input and checks if it contains any spaces. The idea is that the variable should NOT contain any spaces and the code should consequently echo a suitable message.
bash
bash
asked Nov 21 '18 at 15:35
SSen23SSen23
111
111
add a comment |
add a comment |
5 Answers
5
active
oldest
votes
Try this:
#!/bin/bash
if [[ $1 = *[[:space:]]* ]]
then
echo "space exist"
fi
2
Pedantically,==
is the documented pattern matching operator within[[...]]
but=
also works
– glenn jackman
Nov 21 '18 at 16:10
Thanks, this works well when I want to check an input which contains space in between words. But what if I want to check if a string has space characters at the beginning or at the end of the string?
– SSen23
Dec 8 '18 at 10:05
use if [[ $var =~ ^[[:space:]] ]] (begin string) and if [[ $var =~ [[:space:]]$ ]] test space at the end of the string
– Incrivel Monstro Verde
Dec 10 '18 at 15:28
add a comment |
You can test simple glob patterns in portable shell by using case
, without needing any external programs or Bash extensions (that's a good thing, because then your scripts are useful to more people).
#!/bin/sh
case "$1" in
*' '*)
printf 'Invalid argument %s (contains space)n' "$1" >&2
exit 1
;;
esac
You might want to include other whitespace characters in your check - in which case, use *[[:space:]]*
as the pattern instead of *' '*
.
This has always been my favorite method. It's very effective, and not too hard to read.
– Paul Hodges
Nov 21 '18 at 21:15
add a comment |
You can use wc -w
command to check if there are any words. If the result of this output is a number greater than 1, then it means that there are more than 1 words in the input. Here's an example:
#!/bin/bash
read var1
var2=`echo $var1 | wc -w`
if [ $var2 -gt 1 ]
then
echo "Spaces"
else
echo "No spaces"
fi
Note: there is a |
(pipe symbol) which means that the result of echo $var1
will be given as input to wc -w
via the pipe.
Here is the link where I tested the above code: https://ideone.com/aKJdyN
add a comment |
You can use grep
, like this:
echo " foo" | grep 's' -c
# 1
echo "foo" | grep 's' -c
# 0
Or you may use something like this:
s=' foo'
if [[ $s =~ " " ]]; then
echo 'contains space'
else
echo 'ok'
fi
I wouldn't call out to grep, bash can do it as shown.
– glenn jackman
Nov 21 '18 at 16:11
add a comment |
You could use parameter expansion to remove everything that isn't a space and see if what's left is the empty string or not:
var1='has space'
var2='nospace'
for var in "$var1" "$var2"; do
if [[ ${var//[^[:space:]]} ]]; then
echo "'$var' contains a space"
fi
done
The key is [[ ${var//[^[:space:]]} ]]
:
- With
${var//[^[:space:]]}
, everything that isn't a space is removed from the expansion of$var
.
[[ string ]]
has a non-zero exit status ifstring
is empty. It's a shorthand for the equivalent[[ -n string ]]
.
We could also quote the expansion of ${var//[^[:space:]]}
, but [[ ... ]]
takes care of the quoting for us.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53415526%2fhow-to-check-for-space-in-a-variable-in-bash%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
5 Answers
5
active
oldest
votes
5 Answers
5
active
oldest
votes
active
oldest
votes
active
oldest
votes
Try this:
#!/bin/bash
if [[ $1 = *[[:space:]]* ]]
then
echo "space exist"
fi
2
Pedantically,==
is the documented pattern matching operator within[[...]]
but=
also works
– glenn jackman
Nov 21 '18 at 16:10
Thanks, this works well when I want to check an input which contains space in between words. But what if I want to check if a string has space characters at the beginning or at the end of the string?
– SSen23
Dec 8 '18 at 10:05
use if [[ $var =~ ^[[:space:]] ]] (begin string) and if [[ $var =~ [[:space:]]$ ]] test space at the end of the string
– Incrivel Monstro Verde
Dec 10 '18 at 15:28
add a comment |
Try this:
#!/bin/bash
if [[ $1 = *[[:space:]]* ]]
then
echo "space exist"
fi
2
Pedantically,==
is the documented pattern matching operator within[[...]]
but=
also works
– glenn jackman
Nov 21 '18 at 16:10
Thanks, this works well when I want to check an input which contains space in between words. But what if I want to check if a string has space characters at the beginning or at the end of the string?
– SSen23
Dec 8 '18 at 10:05
use if [[ $var =~ ^[[:space:]] ]] (begin string) and if [[ $var =~ [[:space:]]$ ]] test space at the end of the string
– Incrivel Monstro Verde
Dec 10 '18 at 15:28
add a comment |
Try this:
#!/bin/bash
if [[ $1 = *[[:space:]]* ]]
then
echo "space exist"
fi
Try this:
#!/bin/bash
if [[ $1 = *[[:space:]]* ]]
then
echo "space exist"
fi
answered Nov 21 '18 at 15:47
Incrivel Monstro VerdeIncrivel Monstro Verde
41015
41015
2
Pedantically,==
is the documented pattern matching operator within[[...]]
but=
also works
– glenn jackman
Nov 21 '18 at 16:10
Thanks, this works well when I want to check an input which contains space in between words. But what if I want to check if a string has space characters at the beginning or at the end of the string?
– SSen23
Dec 8 '18 at 10:05
use if [[ $var =~ ^[[:space:]] ]] (begin string) and if [[ $var =~ [[:space:]]$ ]] test space at the end of the string
– Incrivel Monstro Verde
Dec 10 '18 at 15:28
add a comment |
2
Pedantically,==
is the documented pattern matching operator within[[...]]
but=
also works
– glenn jackman
Nov 21 '18 at 16:10
Thanks, this works well when I want to check an input which contains space in between words. But what if I want to check if a string has space characters at the beginning or at the end of the string?
– SSen23
Dec 8 '18 at 10:05
use if [[ $var =~ ^[[:space:]] ]] (begin string) and if [[ $var =~ [[:space:]]$ ]] test space at the end of the string
– Incrivel Monstro Verde
Dec 10 '18 at 15:28
2
2
Pedantically,
==
is the documented pattern matching operator within [[...]]
but =
also works– glenn jackman
Nov 21 '18 at 16:10
Pedantically,
==
is the documented pattern matching operator within [[...]]
but =
also works– glenn jackman
Nov 21 '18 at 16:10
Thanks, this works well when I want to check an input which contains space in between words. But what if I want to check if a string has space characters at the beginning or at the end of the string?
– SSen23
Dec 8 '18 at 10:05
Thanks, this works well when I want to check an input which contains space in between words. But what if I want to check if a string has space characters at the beginning or at the end of the string?
– SSen23
Dec 8 '18 at 10:05
use if [[ $var =~ ^[[:space:]] ]] (begin string) and if [[ $var =~ [[:space:]]$ ]] test space at the end of the string
– Incrivel Monstro Verde
Dec 10 '18 at 15:28
use if [[ $var =~ ^[[:space:]] ]] (begin string) and if [[ $var =~ [[:space:]]$ ]] test space at the end of the string
– Incrivel Monstro Verde
Dec 10 '18 at 15:28
add a comment |
You can test simple glob patterns in portable shell by using case
, without needing any external programs or Bash extensions (that's a good thing, because then your scripts are useful to more people).
#!/bin/sh
case "$1" in
*' '*)
printf 'Invalid argument %s (contains space)n' "$1" >&2
exit 1
;;
esac
You might want to include other whitespace characters in your check - in which case, use *[[:space:]]*
as the pattern instead of *' '*
.
This has always been my favorite method. It's very effective, and not too hard to read.
– Paul Hodges
Nov 21 '18 at 21:15
add a comment |
You can test simple glob patterns in portable shell by using case
, without needing any external programs or Bash extensions (that's a good thing, because then your scripts are useful to more people).
#!/bin/sh
case "$1" in
*' '*)
printf 'Invalid argument %s (contains space)n' "$1" >&2
exit 1
;;
esac
You might want to include other whitespace characters in your check - in which case, use *[[:space:]]*
as the pattern instead of *' '*
.
This has always been my favorite method. It's very effective, and not too hard to read.
– Paul Hodges
Nov 21 '18 at 21:15
add a comment |
You can test simple glob patterns in portable shell by using case
, without needing any external programs or Bash extensions (that's a good thing, because then your scripts are useful to more people).
#!/bin/sh
case "$1" in
*' '*)
printf 'Invalid argument %s (contains space)n' "$1" >&2
exit 1
;;
esac
You might want to include other whitespace characters in your check - in which case, use *[[:space:]]*
as the pattern instead of *' '*
.
You can test simple glob patterns in portable shell by using case
, without needing any external programs or Bash extensions (that's a good thing, because then your scripts are useful to more people).
#!/bin/sh
case "$1" in
*' '*)
printf 'Invalid argument %s (contains space)n' "$1" >&2
exit 1
;;
esac
You might want to include other whitespace characters in your check - in which case, use *[[:space:]]*
as the pattern instead of *' '*
.
edited Nov 21 '18 at 21:24
answered Nov 21 '18 at 16:19
Toby SpeightToby Speight
17.2k134367
17.2k134367
This has always been my favorite method. It's very effective, and not too hard to read.
– Paul Hodges
Nov 21 '18 at 21:15
add a comment |
This has always been my favorite method. It's very effective, and not too hard to read.
– Paul Hodges
Nov 21 '18 at 21:15
This has always been my favorite method. It's very effective, and not too hard to read.
– Paul Hodges
Nov 21 '18 at 21:15
This has always been my favorite method. It's very effective, and not too hard to read.
– Paul Hodges
Nov 21 '18 at 21:15
add a comment |
You can use wc -w
command to check if there are any words. If the result of this output is a number greater than 1, then it means that there are more than 1 words in the input. Here's an example:
#!/bin/bash
read var1
var2=`echo $var1 | wc -w`
if [ $var2 -gt 1 ]
then
echo "Spaces"
else
echo "No spaces"
fi
Note: there is a |
(pipe symbol) which means that the result of echo $var1
will be given as input to wc -w
via the pipe.
Here is the link where I tested the above code: https://ideone.com/aKJdyN
add a comment |
You can use wc -w
command to check if there are any words. If the result of this output is a number greater than 1, then it means that there are more than 1 words in the input. Here's an example:
#!/bin/bash
read var1
var2=`echo $var1 | wc -w`
if [ $var2 -gt 1 ]
then
echo "Spaces"
else
echo "No spaces"
fi
Note: there is a |
(pipe symbol) which means that the result of echo $var1
will be given as input to wc -w
via the pipe.
Here is the link where I tested the above code: https://ideone.com/aKJdyN
add a comment |
You can use wc -w
command to check if there are any words. If the result of this output is a number greater than 1, then it means that there are more than 1 words in the input. Here's an example:
#!/bin/bash
read var1
var2=`echo $var1 | wc -w`
if [ $var2 -gt 1 ]
then
echo "Spaces"
else
echo "No spaces"
fi
Note: there is a |
(pipe symbol) which means that the result of echo $var1
will be given as input to wc -w
via the pipe.
Here is the link where I tested the above code: https://ideone.com/aKJdyN
You can use wc -w
command to check if there are any words. If the result of this output is a number greater than 1, then it means that there are more than 1 words in the input. Here's an example:
#!/bin/bash
read var1
var2=`echo $var1 | wc -w`
if [ $var2 -gt 1 ]
then
echo "Spaces"
else
echo "No spaces"
fi
Note: there is a |
(pipe symbol) which means that the result of echo $var1
will be given as input to wc -w
via the pipe.
Here is the link where I tested the above code: https://ideone.com/aKJdyN
answered Nov 21 '18 at 15:48
kiner_shahkiner_shah
1,31721624
1,31721624
add a comment |
add a comment |
You can use grep
, like this:
echo " foo" | grep 's' -c
# 1
echo "foo" | grep 's' -c
# 0
Or you may use something like this:
s=' foo'
if [[ $s =~ " " ]]; then
echo 'contains space'
else
echo 'ok'
fi
I wouldn't call out to grep, bash can do it as shown.
– glenn jackman
Nov 21 '18 at 16:11
add a comment |
You can use grep
, like this:
echo " foo" | grep 's' -c
# 1
echo "foo" | grep 's' -c
# 0
Or you may use something like this:
s=' foo'
if [[ $s =~ " " ]]; then
echo 'contains space'
else
echo 'ok'
fi
I wouldn't call out to grep, bash can do it as shown.
– glenn jackman
Nov 21 '18 at 16:11
add a comment |
You can use grep
, like this:
echo " foo" | grep 's' -c
# 1
echo "foo" | grep 's' -c
# 0
Or you may use something like this:
s=' foo'
if [[ $s =~ " " ]]; then
echo 'contains space'
else
echo 'ok'
fi
You can use grep
, like this:
echo " foo" | grep 's' -c
# 1
echo "foo" | grep 's' -c
# 0
Or you may use something like this:
s=' foo'
if [[ $s =~ " " ]]; then
echo 'contains space'
else
echo 'ok'
fi
edited Nov 21 '18 at 15:54
answered Nov 21 '18 at 15:46
Vladimir KovpakVladimir Kovpak
11.2k43949
11.2k43949
I wouldn't call out to grep, bash can do it as shown.
– glenn jackman
Nov 21 '18 at 16:11
add a comment |
I wouldn't call out to grep, bash can do it as shown.
– glenn jackman
Nov 21 '18 at 16:11
I wouldn't call out to grep, bash can do it as shown.
– glenn jackman
Nov 21 '18 at 16:11
I wouldn't call out to grep, bash can do it as shown.
– glenn jackman
Nov 21 '18 at 16:11
add a comment |
You could use parameter expansion to remove everything that isn't a space and see if what's left is the empty string or not:
var1='has space'
var2='nospace'
for var in "$var1" "$var2"; do
if [[ ${var//[^[:space:]]} ]]; then
echo "'$var' contains a space"
fi
done
The key is [[ ${var//[^[:space:]]} ]]
:
- With
${var//[^[:space:]]}
, everything that isn't a space is removed from the expansion of$var
.
[[ string ]]
has a non-zero exit status ifstring
is empty. It's a shorthand for the equivalent[[ -n string ]]
.
We could also quote the expansion of ${var//[^[:space:]]}
, but [[ ... ]]
takes care of the quoting for us.
add a comment |
You could use parameter expansion to remove everything that isn't a space and see if what's left is the empty string or not:
var1='has space'
var2='nospace'
for var in "$var1" "$var2"; do
if [[ ${var//[^[:space:]]} ]]; then
echo "'$var' contains a space"
fi
done
The key is [[ ${var//[^[:space:]]} ]]
:
- With
${var//[^[:space:]]}
, everything that isn't a space is removed from the expansion of$var
.
[[ string ]]
has a non-zero exit status ifstring
is empty. It's a shorthand for the equivalent[[ -n string ]]
.
We could also quote the expansion of ${var//[^[:space:]]}
, but [[ ... ]]
takes care of the quoting for us.
add a comment |
You could use parameter expansion to remove everything that isn't a space and see if what's left is the empty string or not:
var1='has space'
var2='nospace'
for var in "$var1" "$var2"; do
if [[ ${var//[^[:space:]]} ]]; then
echo "'$var' contains a space"
fi
done
The key is [[ ${var//[^[:space:]]} ]]
:
- With
${var//[^[:space:]]}
, everything that isn't a space is removed from the expansion of$var
.
[[ string ]]
has a non-zero exit status ifstring
is empty. It's a shorthand for the equivalent[[ -n string ]]
.
We could also quote the expansion of ${var//[^[:space:]]}
, but [[ ... ]]
takes care of the quoting for us.
You could use parameter expansion to remove everything that isn't a space and see if what's left is the empty string or not:
var1='has space'
var2='nospace'
for var in "$var1" "$var2"; do
if [[ ${var//[^[:space:]]} ]]; then
echo "'$var' contains a space"
fi
done
The key is [[ ${var//[^[:space:]]} ]]
:
- With
${var//[^[:space:]]}
, everything that isn't a space is removed from the expansion of$var
.
[[ string ]]
has a non-zero exit status ifstring
is empty. It's a shorthand for the equivalent[[ -n string ]]
.
We could also quote the expansion of ${var//[^[:space:]]}
, but [[ ... ]]
takes care of the quoting for us.
answered Nov 21 '18 at 16:41
Benjamin W.Benjamin W.
21.5k135257
21.5k135257
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53415526%2fhow-to-check-for-space-in-a-variable-in-bash%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown