The apt(8) command automatically waits for a lock for 120 seconds (non-interactive) or infinitely.
The apt-get(8) command can be configured to wait as well by passing the -o DPkg::Lock::Timeout=<number of seconds>, where <number of seconds> may also be -1 for infinite.
This avoids any races you'd get by doing the lock yourself and then invoking apt.
Since 20.04, apt can wait for a lock.
The apt(8) command automatically waits for a lock for 120 seconds (non-interactive) or infinitely.
The apt-get(8) command can be configured to wait as well by passing the -o DPkg::Lock: :Timeout= <number of seconds>, where <number of seconds> may also be -1 for infinite.
This avoids any races you'd get by doing the lock yourself and then invoking apt.