date int64 1,220B 1,719B | question_description stringlengths 28 29.9k | accepted_answer stringlengths 12 26.4k | question_title stringlengths 14 159 |
|---|---|---|---|
1,620,033,444,000 |
I want to restrict internet access of a virtual windows machine. I want this machine to be able to reach a certain IP address and upload/dowload files from this server. I set up an OPNsense installation with two NIC: one is connected to the isolated virtual network with the windows PC, the other is a bridged adapter b... |
The solution was very easy. Set up an internal network in Virtualbox adapter settings. Connected both the firewall and the windows PC to this network as first network adapter. Connected a second, bridged adapter to the firewall.
Started the installation of opnsense, assign the bridged adapter as WAN, the internal netw... | block all VM connections but forward to a single host |
1,620,033,444,000 |
I have a whitelist of ip addresses I'm storing in a ipset. I want to craft an iptables rule for my input chain where any IP NOT on the whitelist gets dropped immediately and no rules further down the chain get considered. If a ip matches an address on the whitelist then it continues down the Chain, checking other rule... |
First create a whitelist, with a name (identifier) of choice. I named mine mylist in this example.
$ sudo ipset -N mylist iphash
In my whitelist, I wana allow 10.10.10.0/24 and 10.80.80.0/24 (and then drop everything not listed)
$ sudo ipset -A mylist 10.10.10.0/24
$ sudo ipset -A mylist 10.80.80.0/24
Drop any traf... | iptables: drop any ip not on whitelist, short circuiting chain |
1,620,033,444,000 |
let's say I have a program running that is already using a random tcp/udp port. If I deny connections now via iptables/ufw the port is still open for that programm until I close/reopen it. Is there any way to block the traffic without restarting that programm?
Thank you in advance.
|
iptables -I OUTPUT [-d DEST_IP] -p tcp -m tcp --dport PORT_NUMBER -j DROP
Will stop the application from communicating on that port completely. The fact that the port is still open doesn't really mean anything - it will eventually get closed by timeout.
| block port while its already being used? |
1,620,033,444,000 |
I am using the following code to allow DNS requests, and outgoing traffic to port 443, 22 and 80
However, all the traffic to port 443 and 80 is blocked for some reason
# Allowing DNS lookups (tcp, udp port 53) to server '8.8.8.8'
/sbin/iptables -A OUTPUT -p udp -d 8.8.8.8 --dport 53 -m state --state NEW,ESTABLISHED -j... |
Let's look at just one part of this, where you want to allow outbound connections for ssh on port tcp/22
# Allowing new and established incoming connections to port 22, 80, 443
/sbin/iptables -A INPUT -p tcp -m multiport --dports 22,80,443 -m state --state NEW,ESTABLISHED -j ACCEPT
/sbin/iptables -A OUTPUT -p tcp -m m... | IPTables is blocking all outgoing traffic to http even though I allowed it |
1,620,033,444,000 |
If I open port to a single server on a private network, will that put every computer in my network at security risk? For example, if I have a company desktop and allow ssh into that desktop from a specific IP. Then will that specific IP be able to snoop around to sniff out data on my personal laptop and phones? If so,... |
Credit goes to @John1024
Steps:
Setup DMZ with HPC and port forwarded SSH calls to it (using main router). With added whitelisting of particular IPs. Essentially they are public.
Set up a secondary router to create a private network for my personal devices.
| Securing private network during port forwarding? |
1,620,033,444,000 |
I want the port which my BitTorrent client works on to be open. My PC is connected directly to WAN without a router. I turned off the firewall on ISP side, but the port is still closed. I didn't explicitly install any firewall on my PC either, at least I don't recall it.
Is there any way to tell on which side the prob... |
Try telnet localhost 55133 on your pc, on a local terminal. If you do not connect, it's something blocking the port (or not opening at all) on your pc.
| Port is closed, how am I to tell whether the cause is on my side or on my ISP side? |
1,620,033,444,000 |
What's the difference between "modulate state" and "keep state" in the packet filter (pf) firewall?
I'm using MacOS X Catalina 10.15.5. I have no idea how to check what version of pf is installed on this machine :\
|
Packet Filter originates from OpenBSD:
The initial version of PF was written by Daniel Hartmeier. It
appeared in OpenBSD 3.0, which was released on 1 December 2001.
OpenBSD 3.0:
A new packet filter, PF, featuring NAT capabilities, with a mostly ipf-compatible syntax.
The commit about modulate state predates this r... | pf: difference between 'modulate state' and 'keep state' |
1,620,033,444,000 |
If I check how many connections serverA (192.168.1.1) has open to serverB (192.168.2.1), I get the following response:
[username@serverA ~] $ netstat -n | grep 192.168.2.1
tcp 0 0 192.168.1.1:51846 192.168.2.1:10001 ESTABLISHED
tcp 0 0 192.168.1.1:50872 192.168.2.1:10001 ESTABLI... |
This was solved by a patch release for the application server in use.
| Running netstat on 2 servers checking connections to the other one shows mismatch in number of connections |
1,620,033,444,000 |
I was trying to set firewall rules to my website but I messed up with IP table rules and locked out myself. Now, I can't access to the VPS via SSH. When I try it I get that message:
ssh: connect to host [IP address] port [Port]: Connection timed out
Firstly, I have done those steps for setting the firewall rules. And ... |
There's no way to regain access via ssh. You have to contact your friend and ask him to reset the iptables' rules.
If I can give you a suggestion, I would configure a watchdog using cron or at while configuring iptables, so it won't happen again.
I think you can find useful this answer and this answer on ServerFault.
| Messed up IP table rules and locked myself out while setting firewall on SSH |
1,620,033,444,000 |
I have a VServer, in which I installed the firewall UFW. I scanned the Server with NMAP but I it showed a lot open Ports, which I didnt open. Is it a Bug? Or did I installed UFW false?
Thank you
ufw status:
http://prntscr.com/pgp5db
nmap:
nmap -T4 -A -v *********
//edit I solved the problem. The Problem was I just use... |
Installing UFW and activating the systems unit is not sufficient.
You need to configure it.
The normal default is that everything is denied and UFW therefore disabled after installation (including start of service).
Check ufw status output and be careful not to enable the firewall configuration via UFW or other means ... | NMAP shows open ports even tough I installed the UFW firewall |
1,620,033,444,000 |
I have recently configured my RaspberryPi 3 to only allow connections through VPN. I would however like to open it for SSH connections from anywhere. The rules below should allow traffic on port 22, however as soon as I enable ufw I can no longer connect from anywhere but a local IP (the rules configuring local acces... |
My error was having openvpn active.
| UFW denies SSH even though rules allow [closed] |
1,558,456,132,000 |
Say I wanted to reject packets that are sent to my computer from a specific IP on the network using iptables. Do I need to define the destination of the packet in my command or is it sufficient to just include the source?
For example, say I am working on 126.184.25.25 and I want to reject all TCP packets from 126.184.... |
Do I need to define the destination of the packet in my command or is it sufficient to just include the source?
No and yes it is. If you leave off a setting it has a default. If you don't specify a protocol it defaults to block all, if you don't specify the table (-t) it defaults to filter.
The man page normally state... | Rejecting TCP packets from certain IP on network using iptables |
1,558,456,132,000 |
I need to block all INPUT traffic to port 8090 on the Ubuntu server 16.04.
I used Iptables but it did not work.
Commands I used:
iptables -A INPUT -p tcp --dport 8090 -j DROP
iptables -A INPUT -p tcp --dport 8090 -s <IP> -j ACCEPT
In NAT I have:
Chain DOCKER (2 references)
target prot opt source destination
DNAT t... |
Because of DNAT you're now routing. Your INPUT chain isn't used anymore for this DNATed traffic and it's now the FORWARD chain that is traversed instead. The new destination is 172.21.0.2:8080 and that's what the rules should now care about, not <VM local IP>:8090 anymore.
So with DNAT in place, you should block your ... | Block Docker port and access it to few IP addresses |
1,558,456,132,000 |
This is to document a problem I had with CSF (ConfigServer Firewall) today that cost me a good couple hours.
The problem was that my Ethereum node communicating on port 30303 was being blocked, even though I had added the ports to my config file. It seemed to be working just fine, blocking bad logins and otherwise com... |
The solution was frustrating: systemctl didn't actually refresh the iptables rules. Only csf -ra would do that. So after several hours of beating my head against the wall, I finally ran csf -ra just for kicks and everything came up.
| CSF blocking ethereum traffic, despite valid config |
1,558,456,132,000 |
My goal is to setup a firewall & Intrusion Prevention system using Snort. I have a spare pc available with at least 2 physical NIC's, which ran pfSense having a firewall with Snort, but this time I want to do the setup myself.
So far I managed to install Debian 9 as a headless system with ssh login (and if really need... |
Seems I’ve found a working solution... maybe trivial once you know it, but keep in mind I didn’t know linux nor much networking. So, here.s what I learned:
- you need to use a bridge if you want ‘plug&play’, because it just passes trafic. You could setup a router, but then what comes behind the firewall, needed a diff... | How to setup a firewall between my ISP cable modem/router and my LAN? |
1,558,456,132,000 |
I'm using linux mint and I want to block all incoming connections on port 5210 except 3 IPs. I've searched and went through a lot of threads, and found only results allowing just ranges of LAN IPs, and I cannot find anything related to allowing exactly 3 different IPs that are not in the LAN.
How should I do this or w... |
Allow the three, reject/drop the rest. With iptables from the command line:
iptables -A INPUT -p tcp --dport 5210 --source "$addr1" -j ACCEPT
iptables -A INPUT -p tcp --dport 5210 --source "$addr2" -j ACCEPT
iptables -A INPUT -p tcp --dport 5210 --source "$addr3" -j ACCEPT
iptables -A INPUT -p tcp --dport 5210 -j REJE... | Linux - iptables allow only 3 IPs |
1,558,456,132,000 |
I used svnserve on my centOS server. And I have open port number 3690 on my server. As you can see, the result of command iptables -L is shown as following
Chain INPUT (policy ACCEPT)
target prot opt source destination
ACCEPT all -- anywhere anywhere state RELATE... |
IPtables process the rules from top to the bottom.
Here is the issue:
Take look on the following rules:
REJECT all -- anywhere anywhere reject-with icmp-host-prohibited
ACCEPT tcp -- anywhere anywhere tcp dpt:svn
After Reject all rule all packets are discard... | Why I cannot access the svn server from remote? |
1,558,456,132,000 |
Are things such as Chromium addons and UFW Firewall settings automatically set for all users and future users on Linux distributions ?
|
The firewall, and more generally the network configuration, is a system setting. It applies to all users. Creating new user accounts doesn't change the system settings (apart from the accounts, of course).
Note that a web proxy setting is a user setting, because it's applied by each browser, not by the system.
Chromiu... | Are Chromium addons and UFW Firewall settings set for all users? [closed] |
1,558,456,132,000 |
I made a test machine with old mandrake 9.0 for penetration testing
(had a lot of bugs,so is the ideal).
For security reason i use "host only nic" with virtualbox.
The firewall on machine is disabled but nmap report all port closed except 554!
PORT STATE SERVICE
22/tcp filtered ssh
23/tcp filtered telnet
13... |
Solution found,i use another ip class,so even avoid routing,firewall,etc
I simply change to virtualbox default host-only net(wich is 192.168.56.0/24) the ip of guest.
Now all ports are accessible,i still don't understand why rstp was open....
| why my "host-only" nic on virtualbox refuse the ssh? |
1,558,456,132,000 |
The following is my network topology:
+ +
| |
| |
| |
| +------------------+ |
| | | |
+-----+ firewall +-------+
eth0 | | et... |
The load balancing part of your script says :
If I already know this connection, just let it go the same way than previously
If I don't, send it half of the time on one interface, half of the time on the other one
So you have an equal number of connection going on each interface.
But some connections only have 3 pac... | iptables connection mark not balance |
1,558,456,132,000 |
I have a problem with following thing:
Foreign connection is connection initialized not by my computer.
I would like to accept only foreign connection such that port is 22 or from interval [1000, 1100]
Could you help me please ?
|
For accepting port 22
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
For ports 1000-1100
-A INPUT -m state --state NEW -m tcp -p tcp --dport 1000:1100 -j ACCEPT
if you enter these lines into /etc/sysconfig/iptables file on your linux machine and restart iptables service with service iptables restar... | IP tables - how to configure connections into my compuer |
1,558,456,132,000 |
I’m doing some rules in a machine with the firewall disabled, but when I run rcSuSEfirewall2 a lot of rules and policies are applyed by default:
iptables -L
Chain INPUT (policy DROP)
target prot opt source destination
ACCEPT all -- anywhere anywhere
ACCEPT all -- anywhere ... |
Well, i want to share this workarround, i think is not so elegant as i wanted but it works.
First create a file and call it as you want i.e fwsrv
#!/bin/bash
# Author: Francisco Tapia
#
# /etc/init.d/fwsrv
#
### BEGIN INIT INFO
# Provides: fwsrv
# Required-Start: network
# Should-Start: $null
# Requir... | How to set up a clear SuSE-Firewall? |
1,558,456,132,000 |
I want to deny all outgoing traffic by default, except ssh connections. I added this rules:
ufw default deny outgoing
ufw allow ssh
Then I restarted the firewall by:
ufw disable
ufw enable
Should this do the trick? I also want to deploy a Rails Application on this server. And my hello-world Rails App Server is bo... |
OK. The solution is that my host provider also offers Plesk. And there is a firewall running which somehow overwrites everything i setup manually.
| ufw rule deny default outgoing |
1,558,456,132,000 |
I have an java application that I have been developing. I use a external db server that I can't control. I want to simulate connection error to it, but I'm unable to do it. I have tried to use iptables and tc to create the situation, but after the java program is running it can create a query to the database. If I res... |
The first thing you don't understand is that we can't debug your iptables rules if you don't show them to us.
That being said, I see a potential pitfall. But of course I don't know whether that is your problem.
It's likely that the Java application establishes a TCP connection to the database once and for all when it ... | Block outgoing connection from running process |
1,558,456,132,000 |
I am working in a company what uses Ubuntu Precise on the desktops behind a proxy. The Proxy is available in /etc/environment and set as: http_proxy, https_proxy, ftp_proxy, no proxy and their uppercase versions.
So actually i have a problem with using some applications inside the Bash. If i'm using backportpackage (l... |
When accessing a bzr branch/repository via smart-server directly (via bzr://, but not bzr+ssh:// and not http://), the default port is 4155 according to http://doc.bazaar.canonical.com/bzr.0.18/server.htm
When using bzr+ssh, it will use the ssh port (22)
When using http(s), it will use 80(443).
According to http://do... | What port uses my backportpackage or bzr? |
1,558,456,132,000 |
I try to hardening my server. For doing so, I got a general question: Should I install kernel security patches like selinux and an Anti-Virus with Intrusion Detection Firewall? Does it make sense to combine it or just one of them?
I mean, the patches are known to secure local things like processes etc. from turning in... |
If you are concerned about system integrity, then selinux or grsecurity (or the various similar security packages) are very powerful. Unfortunately, mastering their policies is far from trivial. (Any decent distro that includes SELinux will have predefined policies for all kinds of things, though.) Grsecurity policies... | kernel security and IDS Firewall + AV together or not? |
1,418,633,044,000 |
On a machine called ubuntu1, this is the iptables command:
sudo iptables -A INPUT -p icmp -j DROP
on the other computer (xp1) I can not ping the ubuntu1.So this is OK.
But On ubuntu1 can ping xp1. and I think this is not OK. I do not have problem with ping request but I have problem with ping replay from xp1. Why does... |
The command which you are entering is just for blocking incoming ICMP connection if you want to block outgoing ICMP connection you have to choose output chain
i.e
sudo iptables -A OUTPUT -p icmp -j DROP
| iptables INPUT command |
1,418,633,044,000 |
In the past, I have used the following script to set up a stateful firewall (on a normal x64 Ubuntu machine) without issue:
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -N TCP
iptables -N UDP
iptables -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
iptables -A INPUT -i lo -j ACCEPT
iptables -... |
I had posted this question to the TI Forums as well, and got a response.
Enabling CONFIG_NETFILTER_XT_MATCH_CONNTRACK in the kernel config solved this issue.
I just set CONFIG_NETFILTER_XT_MATCH_CONNTRACK=y in the config, rebuilt with the SDK (instructions here).
After installing the new kernel and modules, the -m con... | How to set up a stateful firewall on an am335x Starter Kit board? |
1,418,633,044,000 |
I have been testing my application which has TCP/UDP ports for peer to peer with the help of server signalling commands for making communication, that works when I have Public IP or Lan IP and not firewall/port blocks are involved. I will name my end points here:
a) PC1 - running in European commission having Lan IP a... |
I think what you should really be asking is:
"... how does Skype traverse complex network topologies where it would seem impossible to connect through these networks which have complex firewalling deployed?"
I'd take a look at this article directly from Skype which explains in pretty good terms the methods they emplo... | Is there any tools which can be used to make ports available from any firewall network? |
1,418,633,044,000 |
I created a RedHat 6.1 VM with EC2. Logged in as root, I installed (unzipped) JDK1.7 in /root/bin/jdk1.7.0 and installed (unzipped) GlassFish 3.1.1 in /root/bin/glassfish3. I set JAVA_HOME and GLASSFISH_HOME in root's .bash_profile and I started GlassFish.
It's definitely running, because if I do a wget localhost:8080... |
I spent some more time with the EC2 security groups. I allowed all incoming TCP ports and it looks like it's working now. I guess I didn't have port 8080 open correctly.
| Can't connect remotely to server running redhat (ec2) |
1,418,633,044,000 |
I m able to telnet locally to mysql process like below:
I have also made sure MySQL process is listening on all IPs by setting bind-address = 0.0.0.0 as evident below:
root@localhost:~# netstat -plutn | grep mysql
tcp 0 0 0.0.0.0:33060 0.0.0.0:* LISTEN 39288/mysqld
tcp 0... |
The server was provisioned by https://cloudpanel.ionos.de/
After login into the portal, there was a firewall option on the webpage dashboard to allow access (incoming traffic) on port 7306.
I don't understand what was preventing the port to be accessed by a remote host if someone can shed some light on the answer.
Aft... | Unable to connect telnet to mysql listen ip port from remote host |
1,418,633,044,000 |
In my college, I can't use the web, because they use Sonicwall network firewalls
How can I tease it? For I use all websites in my college?
Please see the result when I access a website blocked
I already tried use non-proxy but it didn't worked.
Thanks!
|
If outgoing SSH works, you can use SSH tunneling to set up a SOCKS proxy which will effectively bypass the firewall. You will obviously need the following:
Make sure SonicWall doesn't block outgoing SSH connections (TCP port 22). If they do, and you have full control over the SSH server outside of this network (e.g. ... | How can I tease Sonicwall ? |
1,418,633,044,000 |
Here are 2 servers
192.168.0.12
192.168.0.21
there is a service running in 50070 port in server 192.168.0.12
when I do telnet from 192.168.0.21 server it fails:
$telnet 192.168.0.12 50070
Trying 192.168.0.12...
telnet: connect to address 192.168.0.12: Connection refused
When I give hostname then also it fails:
$te... |
Your service is listening on the loopback address only, 127.0.0.1.
When you make a connection from 192.168.0.21 or when you specify the ip address it does not work, as your service is not listening on that ip.
When you use the hostname from 192.168.0.12 it works because it is connecting to the loopback address. This i... | Unable to telnet to a server |
1,418,633,044,000 |
Below are rules for Firewall (Refered from multiple posts) settings, where I want to allow Sending Mails through Applications on my server and allow FTP access of Server. But the Mails have Stopped passing through application after adding these rules. may be something is missing in this. Any help is Appreciated.
*filt... |
You'll probably want that REJECT rule to be at the end of the INPUT chain. I.e., moved to be the last rule before COMMIT.
| IpTables Rules for sending Mails on linux server |
1,418,633,044,000 |
Because the ISP blocks port 80 this prevents my running a web server. As a work-around it's possible to specify a different port for Apache? I believe I've seen mention of using port 81, or some lower ports.
Not for production, just mucking around.
|
Assuming a recent version of Linux and Apache.
To accomplish this configuration change, modify
/etc/httpd/conf/httpd.conf
replacing the
Listen 80
directive with a different port.
As far as ports go, I'd recommend higher. Check a list of TCP and UDP port numbers, go high and stay away from known ports.
| running apache web server on an arbitrary port? |
1,418,633,044,000 |
I need to open port 21 on a Linux (CentOS 5) virtual machine I have. I have tried several Google solutions, but none are working. I was wondering if someone could tell me how to do this.
Below is the output of netstat -tulpn:
tcp 0 0 127.0.0.1:2208 0.0.0.0:* LISTEN 3576... |
I figured it out. I don't have an FTP server running on the machine I am trying to connect to.
| How can I open port 21 on a Linux VM? |
1,418,633,044,000 |
I am having CentOS 6 on my server.
When I disable the firewall via the following commands, ssh starts working fine, however when I turn the firewall back on, ssh stops.
service iptables save
service iptables stop
chkconfig iptables off
Here is the list of iptable rules
[root@server1 ~]# sudo iptables -S
-P INP... |
According to what I read on your screenshot you have several iptables rules and the last one drop all the rest
iptables -A input -j DROP
Before droping the rest of the request you should add a rule to allow ssh into your server
iptables -A input -p 22 -j ACCEPT
| Internet & Ping Working but can't connect via SSH |
1,418,633,044,000 |
The server is supposed to silently ignore any requests (including ping) unless it receives correct credentials with initial request. Nobody else can tell that the host even exists.
I am talking about a very basic "authentication server", a mechanism to selectively make a host visible only to some guests. When the clie... |
If your host doesn't respond to anything, then your options to communicate with it are limited. You aren't going to be able to do things like send it a user name and password, since that would require opening a TCP connection, and that requires traffic in both directions.
You can do port knocking to make the server st... | How do I configure my server to stay hidden unless it receives correct password? |
1,418,633,044,000 |
After upgrading from LMDE2 to LMDE3 Cindy I noticed I could no longer launch the gufw GUI.
The error was:
** (gufw.py:20536): WARNING **: Failed to load shared library 'libwebkit2gtk-4.0.so.37' referenced by the typelib: libGLESv2.so.2: cannot open shared object file: No such file or directory
/usr/share/gufw/gufw/guf... |
In hindsight I think the problem probably had nothing to do with the upgrade, and everything to do with changing to non-free nvidia drivers. (I just hadn't needed to change any firewall settings until after the upgrade.)I checked all of the stated dependencies and everything required seemed to be installed, including ... | gufw GUI fails to launch on LMDE |
1,418,633,044,000 |
Say I have a couple of servers at DigitalOcean and I want them to talk to each others.
DigitalOcean offers a WAN connection and a LAN connection. Problem is that both are insecure. The WAN is the Internet and the LAN is shared by everyone who has a computer (VPS) at DigitalOcean.
So I want to block everything except a... |
I actually found a solution, since I'm on Ubuntu 16.04 and we have systemd, I just created a script snapinitfirewall.service and installed it along my firewall code.
# Documentation available at:
# https://www.freedesktop.org/software/systemd/man/systemd.service.html
[Unit]
Description=Snap! Websites firewall initial... | Two interfaces, both require the firewall to be up before starting |
1,418,633,044,000 |
What is the method to block a machine from establishing connection to an outside ftp server. Both ftp and sftp.
inet, iptables, shutdown service?
|
I'm guessing, but it looks like you want to block connections to port 21 and port 22 . This can be done on the host itself for ftp
iptables -I OUTPUT -p tcp --dport 21 \
-d the.rem.ote.ip \
-m comment --comment "blocked as per ticket##" \
-j REJECT
SFTP, though, is tricky: it shares a port with ssh. If you are oka... | How to stop outbound ftp from being established. centos/ rhel |
1,418,633,044,000 |
I would like to set up a firewall on Linux Debian for IPv6. It is important to use iptables for me. I have tried to change the ipv4 folder to ipv6.
How can I set up iptables for IPv6?
|
In addition to the existing answer.
If you prefer (like I do) to use the syntax from the iptables-save and iptables-restore command ip6tables-save and ip6tables-restore can be used.
The convenient part is that you can share the same rule file for iptables-restore and ip6tables-restore respectively by prefixing all the... | How does the iptables work with IPv6? |
1,478,542,920,000 |
This question is inspired by
Why is using a shell loop to process text considered bad practice ?
I see these constructs
for file in `find . -type f -name ...`; do smth with ${file}; done
and
for dir in $(find . -type d -name ...); do smth with ${dir}; done
being used here almost on a daily basis even if some people ... |
The problem
for f in $(find .)
combines two incompatible things.
find prints a list of file paths delimited by newline characters. While the split+glob operator that is invoked when you leave that $(find .) unquoted in that list context splits it on the characters of $IFS (by default includes newline, but also space ... | Why is looping over find's output bad practice? |
1,478,542,920,000 |
I have the following bash script:
#!/bin/bash
upperlim=10
for i in {0..10}
do
echo $i
done
for i in {0..$upperlim}
do
echo $i
done
The first for loop (without the variable upperlim in the loop control) works fine, but the second for loop (with the variable upperlim in the loop control) does not. Is there any way ... |
The reason for this is the order in which things occur in bash. Brace expansion occurs before variables are expanded. In order to accomplish your goal, you need to use C-style for loop:
upperlim=10
for ((i=0; i<=upperlim; i++)); do
echo "$i"
done
| In bash, is it possible to use an integer variable in a brace expansion |
1,478,542,920,000 |
What is the purpose of the do keyword in Bash for loop syntax? To me, it feels redundant.
for i in `seq 1 2`; do echo "hi"; done
Why isn't the syntax like this?
for i in `seq 1 2`; echo "hi"; done
I'm sure that it does fill a purpose. I just want to learn.
|
Note that that syntax is inherited from the Bourne shell.
After the variable name, you can have either in to have the list of elements explicitly given, or do, to loop over the positional parameters.
for i in 1 2 3
do
echo "$i"
done
Or
set 1 2 3
for i do
echo "$i"
done
Having the do in both cases (even if it's n... | What is the purpose of the "do" keyword in Bash for loops? |
1,478,542,920,000 |
In bash, I know that it is possible to write a for loop in which some loop control variable i iterates over specified integers. For example, I can write a bash shell script that prints the integers between 1 and 10:
#!/bin/bash
for i in {1..10}
do
echo $i
done
Is it possible to instead iterate over a loop control ... |
The correct syntax is as follows:
#!/bin/bash
for fname in a.txt b.txt c.txt
do
echo $fname
done
| In a bash shell script, writing a for loop that iterates over string values |
1,478,542,920,000 |
${!FOO} performs a double substitution in bash, meaning it takes the (string) value of FOO and uses it as a variable name.
zsh doesn’t support this feature.
Is there a way to make this work the same in bash and zsh?
Background:
I’ve got a list of environment variables, like
PATH MAIL EDITOR
and want to first print th... |
Both bash and zsh have a way to perform indirect expansion, but they use different syntax.
It's easy enough to perform indirect expansion using eval; this works in all POSIX and most Bourne shells. Take care to quote properly in case the value contains characters that have a special meaning in the shell.
eval "value=\... | What is the equivalent of bash indirect referencing ${!FOO} in zsh? |
1,478,542,920,000 |
I'd like to find an equivalent of
cmd 1 && cmd 2 && ... && cmd 20
but with commands expressed within a for loop like
for i in {1..20}
do
cmd $i
done
What would you suggest to change in the second expression to find an equivalent of the first?
|
The equivalent to your original sequence would be:
for i in {1..20}
do
cmd $i || break
done
The difference with Amit's answer is the script won't exit, i.e. will execute potential commands that might follow the sequence/loop. Note that the return status of the whole loop will always be true with my suggestion, thi... | How do I replace AND (&&) in a for loop? |
1,478,542,920,000 |
In bash I often use for-loops such as the following
for file in *.type; do
sommecommand "$file";
done;
to perform an operation for all files matching *.type. If no file with this ending is found in the working directories the asterisk is not expanded and usually I will get an error message saying that somecommand... |
Yes, run the following command :
shopt -s nullglob
it will nullify the match and no error will be triggered.
if you want this behaviour by default, add the command in your ~/.bashrc
if you want to detect a null glob in POSIX shell, try
for i in *.txt; do
[ "$i" = '*.txt' ] && [ ! -e '*.txt' ] && continue
done
Se... | Avoiding errors due to unexpanded asterisk |
1,478,542,920,000 |
I need to create a script with a loop through a list of items. I want to insert a string in the script.
I tried:
for i in "
a
b
c";
do
echo "test "$i
done
But that only outputs one string:
test a b c
How would I get this?
testa
testb
testc
(a, b and c are just examples for some longer words, which I got from an O... |
export a="
a
b
c
"
for i in $a; do echo "test$i";done
| for loop with multiline data |
1,478,542,920,000 |
I want to print list of numbers from 1 to 100 and I use a for loop like the following:
number=100
for num in {1..$number}
do
echo $num
done
When I execute the command it only prints {1..100} and not the list of number from 1 to 100.
|
Yes, that's because brace-expansion occurs before parameter expansion. Either use another shell like zsh or ksh93 or use an alternative syntax:
Standard (POSIX) sh syntax
i=1
while [ "$i" -le "$number" ]; do
echo "$i"
i=$(($i + 1))
done
Ksh-style for ((...))
for ((i=1;i<=number;i++)); do
echo "$i"
done
use eva... | bash variables in for loop range [duplicate] |
1,478,542,920,000 |
I need to iterate through every file inside a directory. One common way I saw was using the for loop that begins with for file in *; do. However, I realized that it does not include hidden files (files that begin with a "."). The other obvious way is then do something like
for file in `ls -a`; do
However, iterating... |
You just need to create a list of glob matching files, separated by space:
for file in .* *; do echo "$file"; done
Edit
The above one can rewrite in different form using brace expansion
for file in {.*,*}; do echo "$file"; done
or even shorter: for file in {.,}*; do echo "$file"; done
Adding the path for selected ... | proper way to iterate through contents in a directory [duplicate] |
1,478,542,920,000 |
I have a folder named 'sample' and it has 3 files in it. I want to write a shell script which will read these files inside the sample folder and post it to an HTTP site using curl.
I have written the following for listing files inside the folder:
for dir in sample/*; do
echo $dir;
done
But it gives me... |
Use basename to strip the leading path off of the files:
for file in sample/*; do
echo "$(basename "$file")"
done
Though why not:
( cd sample; ls )
| Loop through a folder and list files |
1,478,542,920,000 |
I need my script to do something to every file in the current directory excluding any sub-directories.
For example, in the current path, there are 5 files, but 1 of them is a folder (a sub-directory).
My script should activate a command given as arguments when running said script. I.e. "bash script wc -w" should give ... |
#!/bin/bash -
for file in "$dir"/*
do
if [ ! -d "$file" ]; then
"$@" "$file"
fi
done
Note that it also excludes files that are of type symlink and where the symlink resolves to a file of type directory (which is probably what you want).
Alternative (from comments), check only for files:
for file in "$dir"/... | Loop through files excluding directories |
1,478,542,920,000 |
I'm trying to write a simple script to retrieve memory and swap usage from a list of hosts. Currently, the only way I've been able to achieve this is to write 3 separate scripts:
for a in {1..9}; do echo "bvrprdsve00$a; $(ssh -q bvrprdsve00$a "echo \$(free -m|grep Mem|/bin/awk '{print \$4}';free -m|grep Swap|/bin/awk ... |
Bash brace expansions could generate the numbers with leading zeros (since bash 4.0 alpha+ ~2009-02-20):
$ echo {001..023}
001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019 020 021 022 023
So, you can do:
for a in {001..218}; do echo "bvrprdsve$a; $(ssh -q bvrprdsve$a "echo \$(free -m|grep ... | How do I get 0-padded numbers in {} (brace expansion)? |
1,478,542,920,000 |
Say I have a below for in loop:
for i in /apps/textfiles/*.txt
do
do something
done
Now say I have 50 files inside /apps/textfiles/
In what order will the files be picked?
|
Filename expansion in Bash is sorting alphabetically.
From the Bash Manual:
Bash scans each word for the characters ‘*’, ‘?’, and ‘[’. If one of these characters appears, then the word is regarded as a pattern, and replaced with an alphabetically sorted list of filenames matching the pattern [...].
It doesn't make a... | In what order does a bash FOR IN loop pick up files in a folder? |
1,478,542,920,000 |
Is there a way to specify multiple variables (not just integers) in for loops in bash? I may have 2 files containing arbitrary text that i would need to work with.
What i functionally need is something like this:
for i in $(cat file1) and j in $(cat file2); do command $i $j; done
Any ideas?
|
First, Don't read lines with for, as there are several unavoidable issues with reading lines via word-splitting.
Assuming files of equal length, or if you want to only loop until the shorter of two files are read, a simple solution is possible.
while read -r x && read -r y <&3; do
...
done <file1 3<file2
Putting ... | Multivariable For Loops |
1,478,542,920,000 |
I have a problem with for loop in bash. For example:
I have an array ("etc" "bin" "var").
And I iterate on this array. But in the loop I would like append some value to the array. E.g.
array=("etc" "bin" "var")
for i in "${array[@]}"
do
echo $i
done
This displays etc bin var (of course on separate lines).
And if I ap... |
It will append "sbin" 3 times as it should, but it won't iterate over the newly added "sbin"s in the same loop.
After the 2nd example:
echo "${array[@]}"
#=> etc bin var sbin sbin sbin
| In a loop over an array, add an element to the array |
1,478,542,920,000 |
I have a folder with several repositories inside. Is there any way I can run git branch or whatever git command inside each folder?
$ ls
project1 project2 project3 project4
And I'd like to have some kind of output like the following
$ command
project1 [master]
project2 [dev]
proje... |
Try this. $1 should be the parent dir containing all of your repositories (or use "." for the current dir):
#!/bin/bash
function git_branches()
{
if [[ -z "$1" ]]; then
echo "Usage: $FUNCNAME <dir>" >&2
return 1
fi
if [[ ! -d "$1" ]]; then
echo "Invalid dir specified: '${1}'"
... | Get git branch from several folders/repos |
1,478,542,920,000 |
I have a bash script which simply docker pushes an image:
docker push $CONTAINER_IMAGE:latest
I want to loop for 3 times when this fails. How should I achieve this?
|
Use for-loop and && break:
for n in {1..3}; do
docker push $CONTAINER_IMAGE:latest && break;
done
break quits the loop, but only runs when docker push succeeded. If docker push fails, it will exit with error and the loop will continue.
| How to loop for 3 times in bash script when docker push fails? |
1,478,542,920,000 |
I know that the SHELL allows variable assignment to take place immediately before a command, such that IFS=":" read a b c d <<< "$here_string" works...
What I was wondering is do such assignments not work when done with compound statements such as loops? I tried something like IFS=":" for i in $PATH; do echo $i; done... |
for is a reserved word and as such follows special rules:
The following words shall be recognized as reserved words:
! { } case do done elif else esac fi for if in then until while
This recognition shall only occur when none of the characters is quoted and when the word is used as:
The first word of a command
The ... | changing IFS temporarily before a for loop [duplicate] |
1,478,542,920,000 |
Is this the correct way to start multiple sequential processings in the background?
for i in {1..10}; do
for j in {1..10}; do
run_command $i $j;
done &
done;
All j should be processed after each other for a given i, but all i should be processed simultaneously.
|
The outer loop that you have is basically
for i in {1..10}; do
some_compound_command &
done
This would start ten concurrent instances of some_compound_command in the background. They will be started as fast as possible, but not quite "all at the same time" (i.e. if some_compound_command takes very little time, t... | Bash: Multiple for loops in Background |
1,478,542,920,000 |
In my directory I have two files with space, foo bar and another file. I also have two files without space, file1 and file2.
The following script works:
for f in foo\ bar another\ file; do file "$f"; done
This script also works:
for f in 'foo bar' 'another file'; do file "$f"; done
But the following script doesn't w... |
For your command line parsing, arrange with the pathname operands to always be the last ones on the command line:
./myscript -a -b -c -- 'foo bar' 'another file' file[12]
The parsing of the options would look something like
a_opt=false b_opt=false c_opt=false
while getopts abc opt; do
case $opt in
a) a_... | Bash for loop with string var containing spaces |
1,478,542,920,000 |
I have a script something like this:
for chain in http https ssh
do
iptables -nvxL $chain | tail -1 | awk '{print $2}'
done
But what I actually want to do is capture the output of the iptables command for each iteration into a different variable, whose name should be the equal to the current value of chain.
So for t... |
In your case, I would use an associative array for that:
declare -A rules
for chain in http https ssh
do
rules[$chain]=$(iptables -nvxL $chain | tail -1 | awk '{print $2}')
done
You can then access the output by dereferencing, as in
printf -- "%s\n" "${rules['http']}"
or
for chain in http https ssh
do
printf... | How can I assign the output of a command to different variables in each loop iteration? |
1,478,542,920,000 |
in my bash script I try to use a number as an input variable for a for loop
I run the script as
./script.sh InputFolder/ Number_of_iterations
the script should work inside the given folder and run a for loop as many times as the Number_of_iterations variable is set to.
But somehow I can't set the variable as an int... |
You can do this two ways:
With ksh93-compatible shells (ksh93, zsh, bash):
for (( i=1;i<=$2;i++ ))
do
echo "Welcome $i times"
done
Here we set i to 1 and loop, incrementing it until it is less than or equal to $2, outputting:
Welcome 1 times
Welcome 2 times
With POSIX shells on GNU systems:
for i in $(seq "$2")
do
... | How to convert an input parameter to integer value in a for loop in bash? [duplicate] |
1,478,542,920,000 |
I have this idea of running a bash script to check some conditions and using ffmpeg to convert all the videos in my directory from any format to .mkv and it is working great!
The thing is, I did not know that a for file in loop does not work recursively (https://stackoverflow.com/questions/4638874/how-to-loop-through-... |
You've got this code:
for file in *.mkv *avi *mp4 *flv *ogg *mov; do
target="${file%.*}.mkv"
ffmpeg -i "$file" "$target" && rm -rf "$file"
done
which runs in the current directory. To turn it into a recursive process you have a couple of choices. The easiest (IMO) is to use find as you suggested. The syntax for... | Converting `for file in` to `find` so that my script can apply recursively |
1,478,542,920,000 |
I have a difficulty getting over this man bash passage.
If the control variable in a for loop has the nameref attribute, the list of words can be a list of shell variables, and a name reference will be established for each word in the list, in turn, when the loop is executed.
Array variables cannot be given the -n a... |
A nameref variable is to a “normal” variable what a symbolic link is to a regular file.
$ typeset -n ref=actual; ref=foo; echo "$actual"
foo
A for loop executes the body with the loop variable (the “control variable”) bound in turn to each word in the list.
$ for x in one two three; do echo "$x"; done
one
two
three
... | Shell variables in a for loop |
1,478,542,920,000 |
I am dealing with a situation where I need to create a comma separated list from an array into a heredoc and remove the last comma. I am using bash for piped into sed which is erasing all commas instead of the last one. A simplified example is as follows:
x=$(for i in a b c; do echo "${i}",; done| sed 's/,$//')
echo ... |
The issue was that, by default, echo adds a new line each time it is called and sed was operating on those new lines. You couldn't see that because, when bash processes $(...), those new lines are converted to spaces. So, to fix the problem while making the smallest change to your approach:
$ x=$(for i in a b c; do... | Remove last comma from a bash for loop generated string |
1,478,542,920,000 |
for i in {0..999999999}; do echo "hi"; done
takes a long time to write it's output, as if all the echos are first executed and then sent to stdout. The effect is even more pronounced with cowfortune instead of echo and makes terminal buffering less likely to be the issue.
So what precisely happens when I execute the ... |
Ordinary for loops always iterate over a static set of strings. This is regardless of whether the strings are generated by brace expansions or by filename globbing patterns, or some other expansion of a variable or command substitution, etc.
For your for loop, you generate the strings to loop over using a brace expans... | How do bash loops work precisely? |
1,478,542,920,000 |
This has probably been asked but the existing answers don't make sense to me. I am running a loop over multiple CSV files in a folder. This folder has non-csv files also and hence I must specify the csv files explicitly. I am modifying the csv files in several ways using awk, cut etc. After I am done, I want to redire... |
for file in TLC*.csv; do
cut -d, -f2- "${file}" > "${file%.*}_prepped.csv"
done
${file%.*} removes everything after the last dot of $file. If you want to remove everything after the first dot, then you would use %%.
Likewise, ${file#*.} (${file##*.}) removes everything before the first (last) dot.
Read more in Pa... | Adding suffix to filename during for loop in bash |
1,478,542,920,000 |
Hello Every one I have script that call other script with while loop
I need to know how to calculate time taken by each loop
like :
Starting NodeManager...
NodeManager Started
Elapsed time: 00:00:10
Starting AdminServer...
AdminServer Started
Elapsed time: 00:01:10
here is the script
#!/bin/bash
set -e
clear
TFILE... |
Bash has a built in "timer". Set the SECONDS variable to 0 (zero) when you want to start timing, and read its value to get the number of seconds elapsed since it was last reset.
| how to calculate time taken (elapsed time) by loop |
1,478,542,920,000 |
I have a file with a lot of lines like this
/item/pubDate=Sun, 23 Feb 2014 00:55:04 +010
If I execute this
echo "/item/pubDate=Sun, 23 Feb 2014 00:55:04 +010" | grep -Po "(?<=\=).*"
Sun, 23 Feb 2014 00:55:04 +010
I get the correct date (all in one line). Now I want to try this with a lot of dates in a xml file. I u... |
Do it this way instead:
while IFS= read -r fecha; do
echo $fecha
done < <(xml2 < podcast | egrep "pubDate" | grep -Po "(?<=\=).*")
Bash will separate "words" to loop through by characters in the Internal Field Separator ($IFS). You can temporarily disable this behavior by setting IFS to nothing for the duration o... | for loop over input lines |
1,478,542,920,000 |
I want a for loop analog for Vifm.
When I don't select any file, I can type :!echo %f and I see the output of echo with the current file name as the argument.
When I select several files, :!echo %f yields output of echo with all selected filenames joined with spaces as the argument.
What if I want to apply any program... |
This will produce the desired output:
:!echo %f | xargs -n 1 echo
Of course you could define a command (e.g. for) for convenient usage:
:com for echo %f | xargs -n 1
Then you can just type:
:for echo
| Vifm: run command on each selected file individually |
1,478,542,920,000 |
I want to keep all files not ending with .bat
I tried
for f in $(ls | egrep -v .bat); do echo $f; done
and
for f in $(eval ls | egrep -v .bat); do echo $f; done
But both approaches yield the same result, as they print everything. Whereas ls | egrep -v .bat and eval ls | egrep -v .bat work per se, if used apart from... |
A few things wrong in your code:
Using unquoted command substitution ($(...)) without setting $IFS
Leaving expansions unquoted is the split+glob operator. The default is to split on space, tab and newline. Here, you only want to split on newline, so you need to set IFS to that as otherwise that means that will not wor... | Command substitution in for loop not working |
1,478,542,920,000 |
How do you iterate through a loop n amount of times when n is specified by the user at the beginning?
I have written a shell script and need to repeat a certain part of it n numbers of times (depending upon how many times the user wishes).
My script so far looks like this:
echo "how many times would you like to print ... |
You can use seq
for i in $(seq 1 "$num")
or your shell may support C-style loops e.g. in bash
for ((i=0; i<$num; i++))
| How do you create a for loop with a changeable number of iterations? |
1,478,542,920,000 |
I found one for loop example online. Now I want to use it in my code but I am not sure how does this loop operates
for entry in "$search_dir"/*
do
echo "$entry"
done
Now I want to ask that
Does it look in search_dir in each iteration and copies files in search_dir to entry variable one file in each iteration?
O... |
When the shell gets to the for-statement, it will expand the value of $search_dir and perform the file name globbing to generate a list of directory entries that will be iterated over. This happens only once, and if the things in $search_dir disappears or if there are new files/directories added to that directory whil... | What happens when files are added/removed in the middle of a "for f in *" sh loop? |
1,478,542,920,000 |
in the idiom
for i in $directories; do
# ...
done
... is the variable $i local or global?
And what if there happens to be a global variable of the same name. Does bash work with the global variable or the one of the for ... in ... header ?
|
for doesn’t introduce its own variable scope, so i is whatever it is on entry to the for loop. This could be global, or local to whatever function declared it as local, or even global but in a sub-shell.
On exit from the for loop, the variable will have the last value it had in the loop, unless it ended up in a sub-sh... | In for loops in bash, is the counter variable local or global? |
1,478,542,920,000 |
The following bash script
#!/bin/bash
startNumber=$(( 1 ))
endNumber=$(( $startNumber + 3 ))
#for number in {$startNumber..$endNumber}
for number in {1..4}
do
echo $number
done
exit 0
gives the desired output
1
2
3
4
However, when I switch the uncommented and commented for loop, the output is
{1..4}
Wha... |
Variables won't expand inside brace expansion. You could do:
for ((number=startNumber; number<=endNumber; number++)); do
echo "$number"
done
Also, there is no reason to use arithmetic expansion for startNumber you should simply do: startNumber=1.
Additionally, you don't need to use $ to expand variables inside a... | Bash script - variables in curly braces [duplicate] |
1,478,542,920,000 |
Consider we have many photos with names like DSC_20170506_170809.JPEG. To rename the photos so that they follow the pattern Paris_20170506_170809.JPEG,
I've wrote the following script that works perfect.
for file in *.JPEG; do mv ${file} ${file/DSC/Paris}; done
My question is , how we can write this script using a wh... |
There's nothing wrong with using a while loop here. You just have to do it right:
set -- *.jpeg
while (($#)); do
mv -- "${1}" "${1/DSC/Paris}"
shift
done
The while loop above is just as reliable as the for loop (it will work with any file names) and while the latter is - in many instances - the most appropriate tool ... | Rename files using a WHILE loop instead of a FOR loop |
1,478,542,920,000 |
I want to run YII_ENV=prod yii kw/test ten times. I tried
$ YII_ENV=prod for x in 1..10 do; yii kw/test done;
-bash: for: command not found
1304682651
(Seemed to run once.) I also tried
$ for x in {1..10} do; YII_ENV=prod yii kw/test done;
-bash: syntax error near unexpected token `YII_ENV=prod'
GNU bash, version 4.... |
First correct the syntax of your command, place the semicolons correctly. Instead of:
for x in 1..10 do; yii kw/test done;
Use (adding a correct brace expansion also):
for x in {1..10}; do yii kw/test; done
Then, add the variable:
for x in {1..10}; do YII_ENV=prod yii kw/test; done
| How do I use a temporary environment variable in a bash for loop? |
1,478,542,920,000 |
I'm having trouble understanding what I need to escape when using sh -c.
Let's say I want to run the for loop for i in {1..4}; do echo $i; done. By itself, this works fine.
If I pass it to eval, I need to escape the $: eval "for i in {1..4}; do echo \$i; done", but I cannot make it work for sh -c "[...]":
$ sh -c "for... |
The usual wisdom is to define the script (after the -c) inside single quotes. The other part you need to use is a shell where the {1..4} construct is valid:
$ bash -c 'for i in {1..4}; do echo $i; done' # also work with ksh and zsh
One alternative to get it working with dash (your sh) is to make the expansion on the... | How to run a loop inside sh -c |
1,478,542,920,000 |
#! /bin/bash
for (( l = 1 ; l <= 50; ++l )) ; do
for (( k = 1 ; k <= 1000; ++k )) ; do
sed -n '$l,$lp' $k.dat >> ~/Escritorio/$l.txt
done
done
The script is located in a folder together with 1000 dat files each one having 50 lines of text.
The dat files are called 1.dat, 2.dat,...., 1000.dat
My ... |
for LINE in {1..50}; do
for FILE in {1..1000}; do
sed -n "${LINE}p" "${FILE}.dat" >>"~/Escritorio/${LINE}.dat"
done
done
In your script you are using single quotes for the sed expression, variables don't expand inside single quotes, you need to use double quotes.
Also there is a one liner with awk tha... | For loop inside another doesn't work |
1,478,542,920,000 |
I have user account on a linux machine which I do not know its exact IP address. But I know a range which it is ran on one of them.
I want to check which server is my desired server. There are some Microsoft servers, some Linux servers and some servers that are down as well.
I have a shell script to check each server:... |
Ctrl-C sends the SIGINT signal to all the processes of the foreground job of your interactive shell. So that sends it to the sh running the script and ssh.
You can make it not kill the shell by adding a:
trap : INT
to the beginning of your script.
You may also want to use the ConnectTimeout option of ssh:
ssh -o Conn... | Continue for loop by keyboard |
1,515,439,233,000 |
I was trying to parse some nginx config
λ tree sites-enabled/ sites-available/
sites-enabled/
├── bank.cwrcoding.com.conf
├── calendar.cwrcoding.com.conf
├── cloud.cwrcoding.com.conf
├── cwrcoding.com.conf
├── drive.cwrcoding.com.conf
├── groups.cwrcoding.com.conf
├── mail.cwrcoding.com.conf
├── sites.cwrcoding.com.co... |
The problem is that your files have DOS/Windows-style line-endings. As a quick work-around, replace:
echo "$(cat "$enabled") |"
With:
echo "$(tr -d '\r' <"$enabled") |"
Here, tr removes the carriage-return character before the file is displayed, avoiding the problem.
If your files are intended to be used on a Unix ... | Why does bash replaces text from command substitution with text thereafter |
1,515,439,233,000 |
I have a list of values, separated by ':' and I want to process them one by one.
When the delimiter is space, there are no problems:
nuclear@korhal:~$ for a in 720 500 560 130; do echo $a; done
720
500
560
130
But after settings IFS (Internal Field Separator) to : , strange things start to happen:
nuclear@korhal:~$ I... |
Keywords aren't recognized after an assignment. So, the for in IFS=blah for ... just runs a regular command called for, if you have one:
$ cat > ./for
#!/bin/sh
echo script for
$ chmod +x ./for
$ PATH=$PATH:.
$ for x in a b c
> ^C
$ foo=bar for x in a b c
script for
But because Bash parses the whole input line bef... | Weird bash behavior when IFS is set for a for loop |
1,515,439,233,000 |
I am executing below script
LOGDIR=~/curl_result_$(date |tr ' :' '_')
mkdir $LOGDIR
for THREADNO in $(seq 20)
do
for REQNO in $(seq 20)
do
time curl --verbose -sS http://dummy.restapiexample.com/api/v1/create --trace-ascii ${LOGDIR}/trace_${THREADNO}_${REQNO} -d @- <<EOF >> ${LOGDIR}/response_${THREADNO} 2>&1
{"n... |
Because you have piped the loop into grep, it must be run in a subshell. This is mentioned in the Bash manual:
Each command in a pipeline is executed in its own subshell, which is a separate process (see Command Execution Environment)
It is possible to avoid that with the lastpipe shell option for the final command ... | Inner for loop when run in background in bash spawns new bash process |
1,515,439,233,000 |
Let's say I have two bash variables that contain binary values:
a=0011 # decimal 3
b=1000 # decimal 8
Is there a way I can loop through all the possible values between $a and $b keeping it binary? Something like:
for blah in $(seq $a $b) ; do
print "Blah is: $blah"
done
So it will output:
Blah is: 0011
Blah is: ... |
seq is not a built-in. It's also not part of the Posix standard. But the usual implementations of seq don't have any ability to sequence in bases other than 10.
In bash, you can specify a range as {start..finish}. However, that also doesn't work in bases other than 10 (although it does work with letters: {a..f} expand... | Bash: For loop with binary range keeping control value binary |
1,515,439,233,000 |
I am using the following counter functionality in a script:
for ((i=1; i <= 100; i++ )); do
printf "\r%s - %s" "$i" $(( 100 - i ))
sleep 0.25
done
is there a way I can pause and resume the counter with keyboard input?
(preferably with the same key - lets say with space)
|
Use read with a timeout -t and set a variable based on its output.
#!/bin/bash
running=true
for ((i=1; i <= 100; i++ )); do
if [[ "$running" == "true" ]]; then
printf "\r%s - %s" "$i" $(( 100 - i ))
fi
if read -sn 1 -t 0.25; then
if [[ "$running" == "true" ]]; then
running=fa... | Bash - pause and resume a script (for-loop) with certain key |
1,515,439,233,000 |
I have a Java program that gets two arguments (a video file name and an image) and outputs a boolean (0 or 1) in the first line:
java -jar myProgram video1.mp4 image.png
> 0
>some extra information...
>other extra information....going on
Now using bash script, I need to iterate through all files in a folder (not file... |
You have much better control when using conditional statements:
for file in *; do
if [[ -f "$file" ]]; then
output=$(java -jar myProgram "$file" image.png | head -n 1)
[[ $output = "0" ]] && cp -- "$file" folder0
[[ $output = "1" ]] && cp -- "$file" folder1
fi
done
EDIT: if you still want to s... | How can I create a Bash conditional script, based on output from a command? |
1,515,439,233,000 |
I frequently execute programs that take a long time on several remote servers:
for NUM in {1..100}; do ssh host-{NUM}.mydomain.com /usr/bin/takesalongtime; done
Most of the time I let this run in background (i.e. in a terminal emulator while doing something else) and wait for it to finish. However, sometimes I need t... |
Find the pid of the shell and send it a sigint. This will not stop the ssh, but when it finishes the shell will handle the signal and end the loop.
$ for i in {1..100}; do ssh -n localhost 'sleep 9;date'; done
in other terminal
$ ps fax
10636 ? S 0:00 | \_ xterm
10638 pts/2 Ss 0:00 ... | Break running for-loop after current iteration |
1,515,439,233,000 |
I have shell scripts in my ~/Shell directory that I want to be run whenever Bash is started up as my usual user account. So what I have done is added the following to ~/.bashrc:
for i in `find ~/Shell/ -name "*.sh"`
do
sh $i
done
but, for whatever reason the functions contained in files with the file extension .s... |
Put this in your .bashrc:
for rc in ~/Shell/*.sh
do
. "$rc"
done
And you're off to the races!
A couple of notes:
The bash (and zsh etc) source command, while readable, is not universal and does not exist in dash, the most posixly correct shell I know. As it stands, this same code can be used to load code into al... | How do I get ~/.bashrc to execute all scripts in my ~/Shell directory using a loop? |
1,515,439,233,000 |
By using find command I got multiple files. Now I want to add all these files as mail attachment. How do I add these files as attachment in single mail?
I want to implement this in script. Do I need to use for loop and store the files in array variables?
EX: I got 3 files results by the following
find . -type f -name ... |
You can do it with mutt like this:
mutt -a $(find . -type f -name "sum*")
If you want to do it non-interactive, try
mutt -s "Subject" -a $(find . -type f -name "sum*") -- [email protected] < /dev/null
If mutt is not installed, here is an example with mail and more tools (e.g. mpack)!
So it should be something like
... | Attach files for sending mail which are the result set of find command |
1,515,439,233,000 |
I have a question with range variables in for loops.
In for loops I know you can use {..} to define a range.
But I want it to be customer definable.
So the script asks for a range value, and I want it to be flexible.
like this:
#!/bin/bash
while true;
do
echo "Some explenation..."
read -p "Possible values... |
The problem is that brace expansion happens before variable expansion. As explained in man bash:
The order of expansions is: brace expansion; tilde expansion,
parameter and variable expansion, arithmetic expansion, and
command substitution (done in a left-to-right fashion); word
splitting; and pathname exp... | Range variables in for loop custom definable |
1,515,439,233,000 |
I'm trying to trigger a beep on the PC speaker for every unique visitor of a website.
After some brainstorming, it seemed to be possible with one line:
for e in `ssh me@mymachine "tail -n 1 -f /var/log/apache2/test.log | awk '{print $1}' | uniq"`; do beep; done
However uniq doesn't output anything as long as stdin is... |
This is what I came finally up with, thanks to the neat Perl command contributed by JJoao:
# kill everything on termination
trap "kill 0" SIGINT SIGTERM
# Make sure the remote processes are killed on exit, see http://unix.stackexchange.com/questions/103699/kill-process-spawned-by-ssh-when-ssh-dies
shopt -s huponexit
... | uniq and bash for loop not writing to stdout before stdin closing (for one-line website visitor notification system) |
1,515,439,233,000 |
I've read up on a few answers here in reference to quoting variables on the shell.
Basically, here's what I'm running:
for f in "$(tmsu files)"; do echo "${f}"; done
this has the expected outcome: a list of files. However, I'm pretty sure they're coming out as a single string. After some reading I realized that this i... |
However, I'm pretty sure they're coming out as a single string.
This is what you get when you use quotes. I can't speak to how zsh is supposed to do it, but the bash manual states as much (section "Word Splitting", under "EXPANSION"):
The shell scans the results of parameter expansion, command substitution, and ... | I don't really understand expansion and quoting on the shell (zsh/bash) |
1,515,439,233,000 |
I want to change all filenames they have the exact length of 16 characters (digits and lower case letters). I tried [0-9a-z]{16} and [0-9a-z]\{16\} for the placeholder regX in the following snippet, but it doesn't work.
for file in <regX>
do
mv "$file" "${file}.txt"
done
|
With extglob
shopt -s extglob
for file in +([0-9a-z])
do
[[ ${#file} == 16 ]] && echo mv "$file" "${file}.txt"
done
+([0-9a-z]) means one or more of [0-9a-z] characters
${#file} gives the length of filename
echo is for dry run, remove once things are fine
| Fetch all filenames with specific number of characters |
1,515,439,233,000 |
I've been given a script to run, but it produces an error when calling find . -depth 1 -type d.
It produces the following error,
find: paths must precede expression: `1'
This is the line in which it fails,
for dir in `find . -depth 1 -type d`
do
....
I have tried quite a few things without success. And I don't r... |
The -depth switch does not take an argument, but -maxdepth does, so:
for dir in `find . -depth -maxdepth 1 -type d`
do
....
should work.
The -depth argument as per the man page means process directory contents first.
| Looping over dirs using `find . -depth 1 -type d` |
1,515,439,233,000 |
I have a huge number of files that are numbered in a way such as file_01_01.out where the first number is the group that the file belongs to, and the second is number of the file in the group - so file_10_07.out is the 7th file in the 10th group.
I want to copy some text from these files and group them in some output ... |
(in adition to @Philippos): Bash is trying to expand variable $i_ instead of $i.
Try ...${i}_...:
for i in {00..21}
do
grep "text" file_${i}_*out > out_$i.txt
done
| Using a For Loop to Sort and Save Files Using Grep |
1,515,439,233,000 |
I try, with no success, to use an awk command inside a for loop.
I've got a variable which contains a series of strings that I want to cut with awk to get the data.
I know how to do that but what I really want is to cut the data successively.
So I've got this variable:
var="data1,data2,data3"
And here where I am righ... |
You can accomplish what you're trying to do by using double quotes in the awk script to inject the shell variable into it. You still want to keep one literal $ in it, which you can do by escaping it with backslash:
echo $(awk -F, "{print \$$i}" <<<$var)
This will expand the $i to 1, 2 and 3 in each of the iterations,... | Awk command inside a for loop |
1,515,439,233,000 |
I'm trying to pass a list of files with a known set of characters to sed for a find and replace.
For a directory containing multiple .xml files:
ls -la
file1.xml
file2.xml
file3.xml
Each containing a matching string:
grep -i foo *
file1.xml <foo/>
file2.xml <foo/>
file3.xml <foo/>
Replace foo with bar using a for... |
You have a flaw in your for loop. Remove the ls command, and add the $f variable as the argument to sed -i, which will edit each filename.xml in place:
for f in *.xml; do sed -i "s|foo|bar|g" "$f"; done
| Use sed to find and replace a string in multiple files [duplicate] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.